C - named pipe for multiple forked children

∥☆過路亽.° 提交于 2019-12-05 20:08:15

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.

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.

The PIPE(7) manual page says that:

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.)

You can have only one pipe, several writers and one reader. But to be able to read correctly you need to have some kind of data structure. What you can do simply is to prefix each message with its length. If a writer want to write something, say the string "hello" then it sends 0x05 and the bytes of the strings. Then the reading is uniform : read one byte to get the length of the byte to read next (two reads for a message). Writing in pipes is atomic provided that you don't write too much; not sure but I think that PIPE_BUF constant is the length that guarantee you the atomicity.

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