4

Possible Duplicate:
Working of fork() in linux gcc
Why does this code print two times?

I want to know the reason behind the output of the below code:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>

int main()
{
   FILE *fp;
   int n;
   printf("%d",45);
   //fflush(stdout);
   if((n=fork())>0){
      printf("in parent\n");  
      exit(0);
   }
   else if(n==0)
       printf("%d",45);
}

Output is

45inparent
4545

If I use fflush, then output is

45inparent
45

Also, I am running on the linux platform

Community
  • 1
  • 1
Vindhya G
  • 1,339
  • 2
  • 21
  • 46
  • A similar post which explains more about the fork call:http://theunixshell.blogspot.in/2013/07/fork-system-call-and-duplicating-buffer.html – Vijay Apr 22 '14 at 10:20

2 Answers2

5

The child process inherits the open file descriptors (stdout in this case) and the buffer associated with it.

  • If you don't flush the buffer before the fork, then the content of the buffer is duplicated (including "45"), and "45" is printed twice.
  • If you flush before the fork, the buffer is emptied and the child gets an empty copy of the buffer, therefore "45" is printed only once by the parent.
Sdra
  • 2,297
  • 17
  • 30
3

The first printf() writes the string 45 in a memory buffer.

During the fork() call, the buffer is virtually duplicated in the child process, so both the parent and the child have 45 in stdout`s buffer.

Flushing that buffer in both processes will write 45 twice.

Arnaud Le Blanc
  • 98,321
  • 23
  • 206
  • 194