管道 - 与多个分叉的子进程通信

Pipe - communicating with multiple forked child processes

我正在编写一个父进程,它需要对来自一组子进程的事件进行计数。 我将使用 pipe() 来实现这一点。

我可以在父级上打开一个管道,然后分叉 4 个子进程,这些子进程将使用同一个管道与父级通信,还是必须创建 4 个不同的管道? (每个子进程 1 个)

重要的是要声明父进程从不与子进程通信。它所做的只是:计算并总结子进程引发事件的速率。

另外:如果我可以使用共享管道,消息的原子性是什么。我是否必须让它们保持一个字节长,或者我是否可以假设两个 4 字节消息不会对其字节进行插值?

您可以使用单个管道。

您无需将自己局限于 single-byte 个事件。

man 7 pipe 在 Linux 状态:

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

(相关:description of write in POSIX。)

Try using named pipe is this example https://www.geeksforgeeks.org/named-pipe-fifo-example-c-program/ Rin reader 然后编写应该完成工作,你还应该考虑消息队列,它是进程之间通信的异步方式

另一种选择是使用一个由 socketpair 创建的数据报 unix 套接字对而不是管道。在这种情况下,每个 write 创建一个单独的数据报,每个 read returns 仅创建一个数据报。这样消息可以大于 PIPE_BUF 并且仍然是原子的。