Search code examples
cfork

Odd behavior of a c program with fork()


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.


Solution

  • 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...