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?
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 printsHello World
.If you flush
cout
before thefork()
, the problem will almost certainly go away.If you use:
You only see one. I guess
fork()
copies whatever output bufferstd::cout
writes to.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.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.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:
you should see only one.
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