Fork()'s Unexpected Branching Behavior
Consider the following code that utilizes the fork() system call:
<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>
Surprisingly, when this program is executed, it outputs 8 dots instead of the expected 6. This discrepancy initially seems puzzling.
Dissecting the Code's Execution
To understand this behavior, we must break down the execution process step by step:
Buffered Output
The crux of the issue lies in the buffered output of printf(). When a process prints, the output is not immediately flushed to the screen. Instead, it is stored in a buffer. This behavior is significant because the fork() system call copies the buffer, resulting in duplicate buffered dots.
A Total of 8 Dots
When the four processes terminate, their buffered dots are flushed, adding them to the single dot printed initially. This results in a total of 8 dots being output.
Avoiding the Issue
To prevent this behavior, one can explicitly flush the output buffer using fflush(stdout) after each printf() call. This ensures that output is immediately sent to the screen, eliminating the discrepancy between the number of processes and the number of printed dots.
The above is the detailed content of Why Does `fork()` Output 8 Dots Instead of 6 in This Code?. For more information, please follow other related articles on the PHP Chinese website!