The fork confuses me

Can someone explain how this code works?

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

Fingerprints:

 HelloWorldHelloWorld 

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

In addition, sometimes he prints:

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

Why is this conclusion?

+8
c fork
source share
3 answers

Reason: buffered output. “Hello” is in the buffer, but not yet extinguished when you make the fork, so the forked process starts with the same buffer, including the same word “Hello”. Then, both the parent and child output are “World,” so the general output of “HelloWorld” is for both of them.

+18
source share

Adding to @ammoQ's answer:

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

will lead you to the expected result.

+4
source share

Fork creates a copy of the process. And printf () can be buffered, when a fork occurs, this buffer will be copied.

A pretty solid explanation here: is fork () more than expected?

+3
source share

All Articles