fork() in c using printf [duplicate]

2020-01-26 10:39发布

There are 2 different programs, they are small for example:

int main()
{
        printf ("print hello");
        fork();
}

int main()
{
        printf ("print hello\n");
        fork();
}

output 1 is: `print helloprint hello

output 2 is:print hello

The question is, why does the one with the \n only print once, and the first one prints it twice?

标签: c fork printf
2条回答
Melony?
2楼-- · 2020-01-26 10:55

Change:

    printf ("print hello");
    fork();

to

    printf ("print hello");
    fflush(stdout);
    fork();

By default, stdout is usually line-buffered. In your example 2) you have the guarantee that stdout is flushed before the fork but in the example 1) it may happen after the fork. Flushing stdout before the fork guarantee you to have the string printed before the fork.

查看更多
We Are One
3楼-- · 2020-01-26 10:57

You're running into the buffering behaviour of your system's printf implementation. In the first case, the string is printed to a buffer, but since there's no newline (and you didn't call fflush), it's just sitting there in that buffer. Then you fork, and both forked buffers are flushed when their respective processes exit.

In the second case, the \n causes the buffer to be flushed before the fork, so there's no output remaining when the forked processes exit.

查看更多
登录 后发表回答