Working of fork() in linux gcc [duplicate]

(Incorporating some explanation from a comment by user @Jack)
When you print something to the “Standard Output” stdout (computer monitor usually, although you can redirect it to a file), it gets stored in temporary buffer initially.

Both sides of the fork inherit the unflushed buffer, so when each side of the fork hits the return statement and ends, it gets flushed twice.

Before you fork, you should fflush(stdout); which will flush the buffer so that the child doesn’t inherit it.

stdout to the screen (as opposed to when you’re redirecting it to a file) is actually buffered by line ends, so if you’d done printf("Hi\n"); you wouldn’t have had this problem because it would have flushed the buffer itself.

Leave a Comment