fork()和输出
我有一个简单的程序:
int main()
{
std::cout << " Hello World";
fork();
}
程序执行后我的输出是: Hello World Hello World
。为什么会发生这种情况,而不是单个 Hello world
?我猜想子进程在后台重新运行,并且输出缓冲区在进程之间共享或者沿着这些行共享,但是是这种情况还是其他事情发生?
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?
这不是你原来想的。输出缓冲区不共享 - 当您执行该叉时,两个进程都会获得相同缓冲区的副本。
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.
这个只会发生,因为cout是缓冲的IO 。如果你使用cerr,这是没有缓冲,你应该只看到消息一次,前叉。
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.