Home > Backend Development > C++ > body text

Why Does `fork()` Produce More Dots Than Expected in This Code?

Susan Sarandon
Release: 2024-11-04 01:31:02
Original
710 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!