Search code examples
cpipeforkposix

Pipe - communicating with multiple forked child processes


I am writing a parent process, that needs to count events from a group of child processes. I am going to use pipe() to achieve this.

Can I open a single pipe on the parent, and then fork 4 child processes that will use that same pipe to communicate with the parent, or must I create 4 different pipes? (1 for each child process)

It is important to state that the parent never communicates with the child processes. All it does is: Count and sum up the rate at which the child processes raise events.

Also: In case I can use a shared pipe, what would the atomicity of the messages be. Do I have to keep them one byte long, or can I assume that two 4 byte messages will not get their bytes interpolated?


Solution

  • You can use a single pipe.

    You don't need to limit yourself to single-byte events.

    man 7 pipe on Linux states:

    PIPE_BUF

    POSIX.1 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 requires PIPE_BUF to be at least 512 bytes. (On Linux, PIPE_BUF is 4096 bytes.)

    (Related: The description of write in POSIX.)