fork() and printf()

百般思念 提交于 2019-12-08 04:37:45

问题


As I understood fork() creates a child process by copying the image of the parent process.

My question is about how do child and parent processes share the stdout stream?

Can printf() function of one process be interrupted by other or not? Which may cause the mixed output.

Or is the printf() function output atomic?

For example:

The first case:

parent: printf("Hello");

child: printf("World\n");

Console has: HeWollorld

The second case:

parent: printf("Hello");

child: printf("World\n");

Console has: HelolWorld

回答1:


printf() is not guaranteed to be atomic. If you need atomicity, use write() with a string, preformatted using s*printf() etc., if needed. Even then, you should make the size of the data written using write() is not too big:

Write requests of {PIPE_BUF} bytes or less shall not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set.




回答2:


stdout is usually line-buffered. stderr is usually unbuffered.




回答3:


The behavior of printf() may vary (depending on the exact details of your OS, C compiler, etc.). However, in general printf() is not atomic. Thus interleaving (as per your 1st case) can occur



来源:https://stackoverflow.com/questions/2131463/fork-and-printf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!