Home >Backend Development >C++ >Why Does My `fork()` Loop Produce More Output 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>
When executed, this program surprisingly outputs 8 dots instead of the expected 6. How is this possible?
To understand the unexpected output, we must delve into the intricacies of the fork() primitive. When fork() is invoked, it creates a near-perfect copy of the current process. The most notable difference (for most purposes) is the different return values for the parent and child processes. However, the code provided ignores these return values, effectively rendering this distinction irrelevant.
Initially, there exists a single process. Subsequently, it creates a second process, resulting in two processes printing a dot and continuing the loop. On their second iteration, each process again creates a copy, leading to four processes that print a dot and then exit. This explains the first six dots.
However, printf() employs output buffering. Hence, the initial dot printed by the two processes is not immediately visible. These dots remain buffered and are duplicated during fork(). It is only when a process exits that the buffered dots are flushed and appear. Thus, four processes outputting a buffered dot, along with one new dot, yields the unexpected output of 8 dots.
To suppress this behavior, fflush(stdout); can be called after each printf() statement, thereby ensuring that the dots are immediately displayed.
The above is the detailed content of Why Does My `fork()` Loop Produce More Output than Expected?. For more information, please follow other related articles on the PHP Chinese website!