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
The child process inherits the open file descriptors (stdout in this case) and the buffer associated with it.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With