为什么fork()导致输出重复?

编程入门 行业动态 更新时间:2024-10-23 14:33:37
本文介绍了为什么fork()导致输出重复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 #include <iostream> #include <unistd.h> #include <stdlib.h> int main() { std::cout << 1; fork(); exit(0); }

fork位于流式传输到cout之后的位置,但是此代码显示11. 为什么?为什么将std::endl添加到cout时代码仅显示1?

The fork is located after streaming into cout, but this code prints 11. Why? And why does the code only print 1 if std::endl is added to cout?

#include <iostream> #include <unistd.h> #include <stdlib.h> int main() { std::cout << 1 << std::endl; fork(); exit(0); }

推荐答案

这是由流缓冲引起的.在流中插入std::endl会导致将其刷新,因此在分叉时,流缓冲区为空.当您不插入std::endl时,直到程序退出,流才会被刷新. fork()导致输出流被复制,包括未刷新的内容.在fork()之后,有2个进程的输出缓冲区未刷新,但包含'1'.它们每个都退出,刷新它们的缓冲区,您会看到"11".

It's caused by stream buffering. Inserting std::endl into the stream causes it to be flushed, so when you fork, the stream buffer is empty. When you don't insert std::endl, the stream doesn't get flushed until program exit. fork() causes the output stream to be duplicated, including unflushed contents. After the fork() there are 2 processes with unflushed output buffers containing the '1'. They each exit, flushing their buffers and you see "11".

更多推荐

为什么fork()导致输出重复?

本文发布于:2023-10-09 06:18:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1474935.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:fork

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!