Home > Article > Backend Development > Why Does `fork()` Produce More Dots Than Expected in This Code?
Why Does fork() Branch More Times Than Expected?
Consider the following code snippet:
<code class="c">#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main(void) { int i; for(i = 0; i < 2; i++) { fork(); printf("."); } return 0; }</code>
This code should produce 6 dots as output, as it forks twice and each process prints one dot. However, it surprisingly outputs 8 dots. Why does this happen?
Fork() and Process Duplication
The fork() function creates a near-perfect duplicate of the current process. The most notable difference is that the return value differs between the parent and child processes.
In this code, the fork() calls create four processes: the original process and three child processes. Each process prints a dot when it is created, accounting for the first six dots.
Buffered Output
However, there is one more catch. printf() uses a buffer to store output until it is flushed or the process exits. In this code, the output is not flushed until the processes exit.
As a result, the dots from the original process and the first child process remain in the buffer during the second fork. When the remaining four processes (two from the first fork and two from the second fork) exit, they flush their buffers, causing the dots to be printed. This brings the total output to 8 dots.
Preventing Buffered Output
To avoid this behavior, you can call fflush(stdout); after each printf() call to force the output to be flushed immediately. However, this can impact performance in some scenarios.
The above is the detailed content of Why Does `fork()` Produce More Dots Than Expected in This Code?. For more information, please follow other related articles on the PHP Chinese website!