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?
Because you called fork() without flushing all buffers first.
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.