C-多个分叉孩子的命名管道 [英] C - named pipe for multiple forked children

查看:65
本文介绍了C-多个分叉孩子的命名管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您通过fork()创建了多个子级,并且与父级通信的方法是命名管道",您是否需要多个命名管道?每个孩子一个?还是可以让孩子读一本书?

If you have multiple children created by fork(), and the method of communication with the parent is "named pipes", do you need multiple named pipes? One for each child? Or can you make one and have the parent read from that?

基本上,您还有什么需要做的吗?我知道,如果几个孩子同时写入同一个命名管道,则可能会导致读取单个孩子的整个邮件时出现问题.有没有办法确保写入是原子的?

Basically, is there anything else you need to do? I understand if several children write to the same named pipe at the same time, it might cause a problem with reading a whole message from a single child. Is there a way to make sure the writes are atomic?

推荐答案

您可以在一个管道中包含多个编写器.但是,正如您所说的,通信是在fork()的子代与父代之间进行的,您实际上可能根本不需要 named 管道.命名管道在文件系统中可见,并且可用于非父/子进程之间的通信.

You can have several writers with a single pipe. However, as you say communication is between fork()ed children and the parent, you might not really need named pipes at all. Named pipes are visible in the file system and can be used for communication between processes that are not parent/child.

关于原子性:如果您编写的文件少于PIPE_BUF(在Linux上,limits.h中不少于512字节,即4096字节),则该写操作是原子的,并且不会混合来自不同编写器的消息.如果编写的内容多于PIPE_BUF,则不要依赖于原子性的写操作.

About atomicity: If you write less than PIPE_BUF (no less than 512 bytes, 4096 bytes on Linux, from limits.h), then the write is atomic and there will be no mixing of messages from different writers. If you write more than PIPE_BUF, then don't rely on the writes being atomic.

PIPE(7)手册页表示:

PIPE_BUF

PIPE_BUF

  POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be
  atomic: the output data is written to the pipe as a contiguous
  sequence.  Writes of more than PIPE_BUF bytes may be nonatomic: the
  kernel may interleave the data with data written by other processes.
  POSIX.1-2001 requires PIPE_BUF to be at least 512 bytes.  (On Linux,
  PIPE_BUF is 4096 bytes.)

这篇关于C-多个分叉孩子的命名管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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