Reputation: 3265
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?
Upvotes: 1
Views: 559
Reputation: 136256
Another option is to use one datagram unix socket pair created with socketpair
instead of a pipe. In this case each write
creates a separate datagram and each read
returns one datagram only. This way messages can be larger than PIPE_BUF
and still be atomic.
Upvotes: 0
Reputation: 1302
Try using named pipe is this example https://www.geeksforgeeks.org/named-pipe-fifo-example-c-program/ Rin the reader and then the written should do the work, you should also think about message quue that is asynchronous way of communicating between process
Upvotes: -2
Reputation: 85767
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 thanPIPE_BUF
bytes may be nonatomic: the kernel may interleave the data with data written by other processes. POSIX.1 requiresPIPE_BUF
to be at least 512 bytes. (On Linux,PIPE_BUF
is 4096 bytes.)
(Related: The description of write
in POSIX.)
Upvotes: 4