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

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

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

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