可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have a simple program:
int main()
{
std::cout << " Hello World";
fork();
}
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?
回答1:
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.
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.
回答2:
standard output uses buffered IO. When the fork()
is called the standard output is not flushed and the buffered content is replicated in the child process. These buffers are flushed when the process exit, resulting in the two outputs that you see.
If you change the program to:
std::cout << " Hello World;" << std::endl;
you should see only one.
回答3:
Because you called fork() without flushing all buffers first.
cout.flush();
fork();
回答4:
The code to output "Hello World"
is only executed once. The issue is that the output buffer isn't flushed. So when you fork the process, "Hello World"
is still sitting in the output buffer. When both programs exit, their output buffers will be flushed and you'll see the output twice.
The easiest way to demonstrate this is by adding a newline at the end of your string, which will cause an implicit flush, or explicitly flush with std::cout.flush();
. Then you'll only see the output once.
回答5:
If you use:
std::cout << " Hello World" << std::flush;
You only see one. I guess fork()
copies whatever output buffer std::cout
writes to.
回答6:
The string is not immediately written to the screen; instead, it's written to an internal buffer. The child process inherits a copy of the output buffer, so when the child's cout
is automatically flushed, Hello World
is printed to the screen. The parent also prints Hello World
.
If you flush cout
before the fork()
, the problem will almost certainly go away.
回答7:
The reason is that the when you invoke std::cout<<
it doesn't really perform the output itself but data is left in a buffer in the system. When you do the fork, both code and data are copied, as well as all the buffers associated. Finally, both father and son flush them to the standard output and thus you see the output duplicated.
回答8:
What you're likely seeing here is an effect of buffering. In general output is buffered until it's explicitly flushed or implicitly done with an action like outputting a new line. Because the output is buffered both copies of the forked process have bufferred output and hence both display it upon the process terminating and flushing the buffer