fork() 和输出 [英] fork() and output

查看:35
本文介绍了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?

推荐答案

这与您最初的想法不一样.输出缓冲区不共享 - 当您执行 fork 时,两个进程都会获得相同缓冲区的副本.因此,在您 fork 之后,两个进程最终都会刷新缓冲区并将内容分别打印到屏幕上.

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,你应该只看到一次消息,pre-fork.

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.

这篇关于fork() 和输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆