C reading and writing with multiple child processes
题
From a parent process in C, I'm running 3 childs, each executing a program.
- Program 1 gets stdin (user input) and prints it to stdout.
- Program 2 gets stdin (should be from program 1), modifies it and prints to stdout.
- Program 3 gets stdin (should be from program 2), modifies it and prints to stdout
I am getting the output of program3, but the modification of program 2 is not showing.
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.
I have checked previous questions but I couldn't find out what I'm doing wrong. Any ideas?
解决方案
Child3 needs to do:
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:
close(pipe2[0]);
close(pipe2[1]);
child2 needs to:
close(pipe2[0]);
and child3 needs to:
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.