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.


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.


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