fork() and output
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?
Solution 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.
Solution 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.
Solution 3:
Because you called fork() without flushing all buffers first.
cout.flush();
fork();