fork()和printf() [英] fork() and printf()

查看:195
本文介绍了fork()和printf()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因为我知道fork()通过复制父进程的图像创建一个子进程。

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

我的问题是如何进行子进程和父进程共享stdout流?

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

一个进程的printf()函数是否被其他进程中断?
这可能导致混合输出。

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

还是printf()函数输出原子?

Or is the printf() function output atomic?

例如:

第一种情况:

parent: printf("Hello");

child: printf("World\n");

Console has: HeWollorld

第二种情况:

parent: printf("Hello");

child: printf("World\n");

Console has: HelolWorld


推荐答案

printf()不能保证是原子的。如果你需要原子性,使用 write()用字符串,使用 s * printf()需要。即使这样,你应该使用 write()写入的数据大小为不要太大

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:


写入请求 {PIPE_BUF} 字节或以下不应与来自在同一管道上执行写入的其他进程的数据交错。大于 {PIPE_BUF} 字节的写入可以具有在任意边界上与其他进程写入的数据交错,而不管 O_NONBLOCK 设置文件状态标志的标志。

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.

这篇关于fork()和printf()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆