8

Can anyone, please, explain how does this code work ?

int main()
{
  printf("Hello");
  fork();
  printf("World");
}

Prints:

HelloWorldHelloWorld

My exact question is, why hello is printed twice. Isn't hello printed first, then fork() is executed ?

Also, sometimes it prints:

 HelloWorld 
// then the reports....process exited with return value 0..etc etc.. then...//
HelloWorld

Why this output ?

perror
  • 7,071
  • 16
  • 58
  • 85
guitar_geek
  • 498
  • 2
  • 9
  • 19

3 Answers3

18

The reason is: buffered output. "Hello" is in the buffer but not yet put out when you do the fork, so the forked process starts with the same buffer including the same word "Hello". Then, both the parent and the child output "World" so the total output is "HelloWorld" for both of them.

Erich Kitzmueller
  • 36,381
  • 5
  • 80
  • 102
4

Adding to @ammoQ answer:

int main()
{
    printf("Hello");
    fflush(stdout);
    fork();
    printf("World");
}

will get you to the expected result.

Jeffery Thomas
  • 42,202
  • 8
  • 92
  • 117
3

Fork creates a copy of the process. And printf() may be buffered when the fork happens, this buffer would be copied.

Pretty solid explanation here: fork() branches more than expected?

Community
  • 1
  • 1
davepmiller
  • 2,620
  • 3
  • 33
  • 61
  • 1
    Hello laser_wizard. It seems like you spotted a duplicate. In this case you should flag the question as a duplicate instead of answering it. – Philipp Aug 05 '14 at 15:09