fork() and output fork() and output unix unix

fork() and output


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.


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.


Because you called fork() without flushing all buffers first.

cout.flush();fork();