问题描述
我以前见过这个问题,但还是有点困惑:我如何创建同一母公司的子进程之间的通信?所有我想此刻要做的就是从第一子进程传递消息到第n子进程。我的想法是在父进程创建n-1个管道,然后家长的两端重定向到下一个子进程。我想不通的是,我们将如何重定向从父两端如果下一个子进程还没有被创造出来的?我觉得有一个在我处理这个方法的问题。
I've seen this question before, but still a bit confused: how would I create communication between child processes of the same parent? All I'm trying to do at the moment is passing a message from the first child process to the nth child process. My idea is to create n-1 pipes in the parent process and then redirect the parent's ends to the next child process. What I can't figure out is, how would we redirect the ends from the parent if the next child process hasn't been created? I feel there's an issue in the way I'm approaching this.
编辑:我的目标是打印从第一子进程传递给最后一个消息。这是一个简单的程序。
My goal is to print the message that was passed from the first child process to the last one. It's a simple program.
推荐答案
您不必先创建过程。该解决方案如下:首先创建所有需要的管道,将它们保存在一些阵列。然后,你做了叉
,重定向输入和输出流(子进程)因此,关闭未使用的管端并执行 EXEC
。没有相应的流程可以存在管道,他们有缓冲区,所以你可以写一个管道,而没有人还在读书,马上就好。
You don't need to create the processes first. The solution is as follows: you first create all the needed pipes, save them in some array. Then you do a fork
, redirect input and output streams (for the child process) accordingly, close unused pipe ends and perform an exec
. Pipes can exist without the corresponding processes, they have buffers, so you can write to a pipe while nobody's still reading, it will be ok.
您只应 EXEC
做之前要注意关闭未使用的ID的。并注意写入一个烟斗的输入端点(所有输入端点)可能成为封闭的:它可能会导致 SIGPIPE
You should just be aware of closing unused id's before doing exec
. And be careful writing to a pipe which input endpoints (all the input endpoints) could become closed: it could result in a SIGPIPE
.
这篇关于用C子进程之间的管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!