从C中的父进程,我运行3个子节点,每个子节点执行一个程序。
程序1获取stdin(用户输入)并将其打印到stdout。 程序2获取stdin(应该来自程序1),修改它并打印到stdout。 程序3获取stdin(应该来自程序2),修改它并打印到stdout我得到program3的输出,但程序2的修改没有显示。
以下是来自父母的相关代码:
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); } } }程序使用fgets和printf进行读/写。
我已经检查了以前的问题,但我无法找出我做错了什么。 有任何想法吗?
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 stdoutI 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需要做:
dup2(pipe2[0], 0); // child3 uses pipe2[0] for reading您还需要关闭孩子在每个孩子中不使用的所有管道。 所以child1需要:
close(pipe2[0]); close(pipe2[1]);child2需要:
close(pipe2[0]);和child3需要:
close(pipe1[0]); close(pipe1[1]); close(pipe2[1]);并且父母需要关闭所有管道,因为它会分叉所有孩子。
所有这些关闭都是必需的,以便当管道中的前一个程序关闭管道时,进程将读取EOF ,因为管道在它打开的所有进程关闭之前并未真正关闭。
Child3 needs to do:
dup2(pipe2[0], 0); // child3 uses pipe2[0] for readingYou 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.
更多推荐
发布评论