C程序对三个命令执行管道

我必须编写一个程序来执行与du |相同的操作 排序| 在命令行的会做,但我卡住了,我的程序不工作。 现在的输出是112。 并且该程序不会终止。 请帮忙,我不知道该怎么办!

int main(void) { int fd[2]; int fd1[2]; int pid; if (pipe(fd) == -1) { perror("Pipe"); exit(1); } switch (fork()) { case -1: perror("Fork"); exit(2); case 0: dup2(fd[1], STDOUT_FILENO); close(fd[0]); close(fd[1]); execl("/usr/bin/du", "du", (char *) 0); exit(3); } if (pipe(fd1) == -1) { perror("Pipe"); exit(1); } switch (fork()) { case -1: perror("Fork"); exit(2); case 0: dup2(fd[0], STDIN_FILENO); dup2(fd1[1], STDOUT_FILENO); close(fd[0]); close(fd[1]); close(fd1[0]); close(fd1[1]); execl("/usr/bin/sort", "sort", (char *) 0); exit(3); } close(fd[0]); close(fd[1]); switch (fork()) { case -1: perror("Fork"); exit(2); case 0: dup2(fd1[0], STDIN_FILENO); close(fd1[0]); close(fd1[1]); execl("/usr/bin/head", "head", (char *) 0); exit(3); } 

}

head成为你的父进程sort – 它的子进程dusort子进程 ,或者head孙子

你需要两个管道,因此,两个arrays – fd和fd1。 让fd管道与head连接排序 ,fd1- dusort连接

您将需要一个大的switch语句,它将确定您当前是否在父进程( head ,pipe(fd)不为0)或子进程( sort ,pipe(fd)为0)。 如果您处于排序状态 ,则需要创建fd1管道并运行孙子进程du 。 现在,由于您再次有两个进程(总共三个),您需要根据您的位置设置管道 – 无论您是孙子进程还是子进程。 您可以使用与管道fd类似的switch语句。 这里的技巧是正确设置fd1管道的输入和输出。

您的代码必须执行以下操作:

 int main(void) { int fd[2]; // sort <===> head int fd1[2]; // du <===> sort pipe(fd); switch (fork()) { case 0: // Are we in sort? pipe(fd1); // If yes, let's make a new pipe! switch (fork()) { case 0: // Are we in du? dup2(fd1[1], STDOUT_FILENO); close(fd1[0]); close(fd1[1]); execl("/usr/bin/du", "du", (whatever directory), NULL); exit(1); default: /* If not in du, we're in sort! in the middle! Let's set up both input and output properly. We have to deal with both pipes */ dup2(fd1[0], STDIN_FILENO); dup2(fd[1], STDOUT_FILENO); close(fd1[0]); close(fd1[1]); execl("/usr/bin/sort", "sort (flags if needed)", (char *) 0); exit(2); } exit(3); default: // If we're not in sort, we're in head dup2(fd[0], STDIN_FILENO); close(fd[0]); close(fd[1]); execl("/usr/bin/head", "head (flags if needed)", (char *) 0); exit(4); } }