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条回答
聊天终结者
2楼-- · 2019-01-07 16:22

Because you called fork() without flushing all buffers first.

cout.flush();
fork();
查看更多
乱世女痞
3楼-- · 2019-01-07 16:27

This isn't quite what you thought originally. The output buffer is not shared - when you execute the fork, both processes get a copy of the same buffer. So, after you fork, both processes eventually flush the buffer and print the contents to screen separately.

This only happens because cout is buffered IO. If you used cerr, which is not buffered, you should only see the message one time, pre-fork.

查看更多
登录 后发表回答