Why does fork() result in duplicated output? [duplicate]

被刻印的时光 ゝ 提交于 2020-01-14 07:46:37

问题


#include <iostream>
#include <unistd.h>
#include <stdlib.h>

int main() {
    std::cout << 1;
    fork();
    exit(0);
}

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);
}

回答1:


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".



来源:https://stackoverflow.com/questions/36502046/why-does-fork-result-in-duplicated-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!