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 ?
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.
Adding to @ammoQ answer:
int main()
{
printf("Hello");
fflush(stdout);
fork();
printf("World");
}
will get you to the expected result.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With