OS: Linux, Language: pure C
I\'m moving forward in learning C programming in general, and C programming under UNIX in a special case.
I detected a strange (f
fork()
effectively creates a copy of the process. If, before calling fork()
, it had data that was buffered, both the parent and child will have the same buffered data. The next time that each of them does something to flush its buffer (such as printing a newline in the case of terminal output) you will see that buffered output in addition to any new output produced by that process. So if you are going to use stdio in both the parent and child then you should fflush
before forking, to ensure that there is no buffered data.
Often, the child is used only to call an exec*
function. Since that replaces the complete child process image (including any buffers) there is technically no need to fflush
if that is really all that you are going to do in the child. However, if there may be buffered data then you should be careful in how an exec failure is handled. In particular, avoid printing the error to stdout or stderr using any stdio function (write
is ok), and then call _exit
(or _Exit
) rather than calling exit
or just returning (which will flush any buffered output). Or avoid the issue altogether by flushing before forking.