Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this code print two times? [duplicate]

Possible Duplicate:
Working of fork() in linux gcc

#include <stdio.h>

void main ()
{
  printf ("ciao");
  fork ();
}

I have some ideas about C optimization but I'm not sure. Hope you know the answer.

like image 332
gc5 Avatar asked Mar 06 '12 10:03

gc5


2 Answers

The code will probably print "ciao" twice as standard output is buffered IO so the internal buffer for standard output will be replicated in the child process and both buffers flushed when each process, the parent and child, exits.

It is unrelated to optimization.

like image 186
hmjd Avatar answered Oct 20 '22 14:10

hmjd


when fork() is called, both parent and child process inherit it and therefore they both will

print out "ciao" when they flush the buffer. If you call fflush(stdout);

before calling fork it will print only once

like image 28
karthik gorijavolu Avatar answered Oct 20 '22 14:10

karthik gorijavolu