C - named channel for multiple split children

If you have multiple children created by fork () and the parent communication method is "named pipes" do you need multiple named pipes? One for each child? Or can you do this and parental read?

Basically, is there anything else you need to do? I understand that if multiple children are writing to the same channel at the same time, it can cause a problem reading the whole message from one child. Is there a way to make sure the records are atomic?

+3


source to share


2 answers


You can have multiple contributors with the same feed. However, as you say, the communication between the children of fork () ed and the parent, you don't really need named pipes at all. Named pipes are visible on the file system and can be used to communicate between processes that are not parent / child.

On atomicity: if you write less than PIPE_BUF (at least 512 bytes, 4096 bytes on Linux, from limits.h), then the writing is atomic and there will be no mixing of messages from different authors. If you write more than PIPE_BUF, then don't rely on the records being atomic.



The PIPE (7) page reports 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.)

      

+4


source


You can only have one pipe, multiple authors, 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 prefix each message with its length. If the writer wants to write something, say the line "hello", then he will send 0x05 and bytes of lines. Then the read is uniform: read one byte to get the length of the byte to read further (two reads per message). Writing in pipes is atomic if you don't write too much; not sure, but I think the constant PIPE_BUF

is the length that guarantees you atomicity.



0


source







All Articles