printf anomaly after “fork()”

前端 未结 3 1046
轻奢々
轻奢々 2020-11-21 04:57

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

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-21 05:46

    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.

提交回复
热议问题