[英]C reading and writing with multiple child processes
From a parent process in C, I'm running 3 childs, each executing a program. 通过C中的父进程,我正在运行3个子进程,每个子进程都执行一个程序。
I am getting the output of program3, but the modification of program 2 is not showing. 我正在获取program3的输出,但是未显示对program 2的修改。
Below is the relevant code from the parent: 以下是父级的相关代码:
if((child1 = fork()) < 0){
/*fatal*/
}
else if(child1 == 0){ //inside child 1
dup2(pipe1[1], 1); //child 1 uses pipe1[1] for writing
close(pipe1[0]);
execl("program1.out", (char *)0);
}
else{
if((child2 = fork()) <0){
/*fatal*/
}
else if(child2 == 0){ //inside child 2
close(pipe1[1]);
dup2(pipe1[0], 0); //child2 uses pipe1[0] for reading
dup2(pipe2[1], 1); //child2 uses pipe[1] for writing
execl("program2.out", (char *)0);
}
else{
if((child3 = fork()) <0){
/*fatal*/
}
else if(child3 == 0){ //inside child 3
close(pipe2[1]);
close(pipe1[0]);
execl("program3.out", (char *)0);
}
else{ //inside parent
wait(NULL);
}
}
}
The programs are using fgets and printf for reading/writing. 程序使用fgets和printf进行读取/写入。
I have checked previous questions but I couldn't find out what I'm doing wrong. 我已经检查了先前的问题,但找不到我做错了什么。 Any ideas? 有任何想法吗?
Child3 needs to do: Child3需要执行以下操作:
dup2(pipe2[0], 0); // child3 uses pipe2[0] for reading
You also need to close all the pipes that a child doesn't use in each child. 您还需要关闭一个孩子没有在每个孩子中使用的所有管道。 So child1 needs to: 因此,child1需要:
close(pipe2[0]);
close(pipe2[1]);
child2 needs to: child2需要:
close(pipe2[0]);
and child3 needs to: 而child3需要:
close(pipe1[0]);
close(pipe1[1]);
close(pipe2[1]);
And the parent needs to close ALL the pipes after it forks all the children. 在分叉所有孩子之后,家长需要关闭所有管道。
All these closes are needed so that the processes will read EOF
when the previous program in the pipeline closes the pipe, because a pipe isn't really closed until all processes that have it open close it. 所有这些关闭都是必需的,以便当管道中的上一个程序关闭管道时,进程将读取EOF
,因为直到打开管道的所有进程都将其关闭,管道才真正关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.