0

i wanted to find someone that can explain this to me. I have this program:

int main(int argc, char *argv[]){
  printf("P ");
  if(fork()==0)
     printf("C ");
  return 0;
}

The result of this program is: P P C

What's the reason for that second "P" ?

César Pereira
  • 249
  • 4
  • 17

1 Answers1

3

IO buffering is the reason. printf is not printing the text right away, but waiting for newline, fflush or the end of the program to actually print it. But the buffer for the "future-to-print" text is in the memory that is getting duplicated by fork, so both processes receive it. And in the end both are printing it.

Eugene Sh.
  • 17,802
  • 8
  • 40
  • 61