Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fork is confusing me [duplicate]

Tags:

c

fork

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 ?

like image 431
guitar_geek Avatar asked Aug 05 '14 14:08

guitar_geek


3 Answers

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.

like image 98
Erich Kitzmueller Avatar answered Nov 07 '22 12:11

Erich Kitzmueller


Adding to @ammoQ answer:

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

will get you to the expected result.

like image 30
Jeffery Thomas Avatar answered Nov 07 '22 11:11

Jeffery Thomas


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?

like image 3
davepmiller Avatar answered Nov 07 '22 10:11

davepmiller