0

In my homework I should explain what is happening in the following code:

#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(){
    int x = 1; 
    if(fork() == 0){// child
        printf("printf1: x=%d\n", ++x);// add then print
    }
    printf("printf2: x=%d\n", --x);
    exit(0);  
}

It's pretty straightforward and easy to understand. Most of the time I get the following output:

printf2: x=0
printf1: x=2
printf2: x=1

This means that the parent process was completed before the child and the child became a zombie process. But sometimes I get the following output:

printf1: x=2
printf2: x=1

After printing that the program freezes (It does not print anything and does not stop). I am running the program on Ubuntu. Any explanation will be appreciated.

6
  • after the program 'freezes' what happens if you push the 'enter' button? Are you getting the prompt or not? Commented May 18, 2020 at 2:09
  • Are you running that program from a shell or an IDE? Commented May 18, 2020 at 4:23
  • @Serge Yes, I am getting the prompt after pressing enter. Commented May 18, 2020 at 10:59
  • @rici I am running the program form a shell. Commented May 18, 2020 at 10:59
  • It appears that the child process prints its output after the prompt is displayed. I didn't notice that. Commented May 18, 2020 at 11:07

1 Answer 1

3

You have 3 processes writing to your terminal: parent, child and the shell interpreter. The parent process and the shell have "syncronized" output, but the child process may interleave its output with either of those. What you may perceive as a hanged process, may actually only be mangled output.

When you think it has hanged, you may try to enter a command and press enter...

Sign up to request clarification or add additional context in comments.

3 Comments

Not sure I understand what you mean with the synchronized output. Child and parent processes prints normally on the terminal even when they are working simultaneously. I don't understand why the output is mangled.
@Nour0700 Think about what happens if the parent process finishes before the child process. Then the parent process exits, and the shell takes over and print its prompt. Then the child process prints its output and exits. But there's no "synchronization" between the child process and the shell, so no new prompt will be printed. That could make it seem like the program just hangs. You need to look at the full output in the window. And press the Enter key in the shell to get a new prompt.
@Someprogrammerdude Now I understand. It's not hanging it just printing the output after the prompt. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.