fork() and output

2019-01-07 15:30发布

I have a simple program:

int main()
{
    std::cout << " Hello World";
    fork();
}

After the program executes my output is: Hello World Hello World. Why does this happen instead of a single Hello world? I'm guessing that the child process is rerun behind the scenes and the output buffer is shared between the processes or something along those lines, but is that the case or is something else happening?

8条回答
Fickle 薄情
2楼-- · 2019-01-07 16:05

The string is not immediately written to the screen; instead, it's written to an internal buffer. The child process inherits a copy of the output buffer, so when the child's cout is automatically flushed, Hello World is printed to the screen. The parent also prints Hello World.

If you flush cout before the fork(), the problem will almost certainly go away.

查看更多
做个烂人
3楼-- · 2019-01-07 16:09

If you use:

std::cout << " Hello World" << std::flush;

You only see one. I guess fork() copies whatever output buffer std::cout writes to.

查看更多
叼着烟拽天下
4楼-- · 2019-01-07 16:10

The code to output "Hello World" is only executed once. The issue is that the output buffer isn't flushed. So when you fork the process, "Hello World" is still sitting in the output buffer. When both programs exit, their output buffers will be flushed and you'll see the output twice.

The easiest way to demonstrate this is by adding a newline at the end of your string, which will cause an implicit flush, or explicitly flush with std::cout.flush();. Then you'll only see the output once.

查看更多
做个烂人
5楼-- · 2019-01-07 16:12

The reason is that the when you invoke std::cout<< it doesn't really perform the output itself but data is left in a buffer in the system. When you do the fork, both code and data are copied, as well as all the buffers associated. Finally, both father and son flush them to the standard output and thus you see the output duplicated.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-07 16:15

standard output uses buffered IO. When the fork() is called the standard output is not flushed and the buffered content is replicated in the child process. These buffers are flushed when the process exit, resulting in the two outputs that you see.

If you change the program to:

std::cout << " Hello World;" << std::endl;

you should see only one.

查看更多
贪生不怕死
7楼-- · 2019-01-07 16:20

What you're likely seeing here is an effect of buffering. In general output is buffered until it's explicitly flushed or implicitly done with an action like outputting a new line. Because the output is buffered both copies of the forked process have bufferred output and hence both display it upon the process terminating and flushing the buffer

查看更多
登录 后发表回答