Home » Linux » The behavior of the fork() system call on Linux in this code [duplicate]

The behavior of the fork() system call on Linux in this code [duplicate]

Posted by: admin November 29, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:

When you call fork() the operating system creates a copy of the current processes entire memory (it doesn’t actually copy the memory since it can use the MMU to do this efficiently).

Since stdout is buffered by default it will only print the message once a newline characters is written or the stream is flushed. When you fork a new process the current write buffer (containing “Test “) will also be duplicated in the new process. This will then be printed once the process exits since that implicitly closes (and flushes) stdout.
If you replace the printf("%s", "Test "); with printf("%s\n", "Test "); or add a fflush(stdout); call before the fork() you will see the expected output.

Questions:
Answers:

At the point where you call fork, both processes have the string “Test ” in their buffers for the standard output. When each process exits, they both flush this text to the output (see exit for explanation). You could (as suggested) add a newline to the buffer (and it would happen to come out because of the buffering — see setbuf for explanation). Or you could call fflush(stdout) before the fork and get exactly what you asked for – the “Test ” string.