Fork in C

Thursday, July 04, 2013 , 2 Comments

Did you try this program:

#include &ltstdio.h&gt
#include &ltsys/types.h&gt
#include &ltunistd.h&gt
int main(void)
{    
int i;    
      for(i = 0; i < 2; i++)    
      {        
        fork();        
        printf(".");    
       }    
return 0;
}

How many dots will this program print.
If you analyse and count , you will come up with a total of 6 dots.
But in real after you execute you will see not 6 but 8 dots printed on the console.

The reason for this is :
So, at first, there is one process. That creates a second process, both of which print a dot and loop. On their second iteration, each creates another copy, so there are four processes print a dot, and then exit. So we can easily account for six dots, like you expect.

However, what printf() really does is buffer its output. So the first dot from when there were only two processes does not appear when written. Those dots remain in the buffer—which is duplicated at fork(). It is not until the process is about to exit that the buffered dot appears. Four processes printing a buffered dot, plus the new one gives 8 dots.

If you wanted to avoid that behavior, call fflush(stdout); after printf().

2 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. I didn't still understand why it displays 8 dots rather than 6! Kindly help.

    ReplyDelete