Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

buffering mechanism when fork is used in c [duplicate]

Tags:

c

file-io

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

like image 865
Vindhya G Avatar asked Oct 28 '25 04:10

Vindhya G


2 Answers

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.
like image 52
Sdra Avatar answered Oct 30 '25 19:10

Sdra


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.

like image 43
Arnaud Le Blanc Avatar answered Oct 30 '25 19:10

Arnaud Le Blanc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!