Home > Article > Backend Development > Why Does This C Program Print 8 Dots Instead of 6 When Using fork()?
fork() Bifurcation Dilemma
In the realm of multiprocess programming, the fork() function reigns supreme. However, its behavior can sometimes perplex the uninitiated. Consider the following code:
<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>
Upon execution, this program outputs not 6 dots as one might expect, but an astonishing 8 dots. How is this possible?
Delving into the fork() Abyss
The answer lies in the intricate workings of fork(). This function essentially creates a near-perfect duplicate of the current process, including its memory and open file descriptors. The primary difference is in the return value, which differs between parent and child processes.
In our example, the initial process creates a second process through the first fork(). Both these processes then print a dot, before looping and forking again. After the second fork(), there are four processes, each of which prints a dot before exiting. Thus, we can account for six dots.
However, the plot thickens with the hidden nature of printf(). By default, printf() buffers its output, delaying its actual display. As a result, the first dot printed before the first fork() call remains unseen. This hidden dot, along with the four buffered dots from the parent and three child processes after the second fork(), results in the final tally of 8 dots.
To Avoid the Buffered Maze
To circumvent this behavior and ensure that printf() outputs immediately, the fflush(stdout) function can be employed after each printf() call. This forces the buffered output to be written, preventing dots from vanishing into the shadows.
The above is the detailed content of Why Does This C Program Print 8 Dots Instead of 6 When Using fork()?. For more information, please follow other related articles on the PHP Chinese website!