Reputation: 1573
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?
Upvotes: 3
Views: 1453
Reputation: 4611
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.)
Upvotes: 4
Reputation: 36401
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.
Upvotes: 0