问题描述
#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()导致输出重复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!