日期:2014-05-16  浏览次数:20831 次

[求助]多个pipe怎么写
我想用C语言实现一下 ls -l | more | wc,写的代码如下,但没有输出,不知道哪里错了,请各位帮帮忙,谢谢各位。
C/C++ code

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int main()
{
    pid_t pid[3];
    int pipe_fd[2];
    int pipe_fd2[2];
    int status;

    char *prog1[3] = {"/bin/ls", "-l", NULL};
    char *prog2[2] = {"/bin/more", NULL};
    char *prog3[2] = {"/usr/bin/wc", NULL};

    if(pipe(pipe_fd) < 0){
        perror("pipe 1 failed");
    }
    if(pipe(pipe_fd2) < 0){
            perror("pipe 2 failed");
        }
    if((pid[0] = fork()) < 0){
        perror("fork failed");
    }
    if(pid[0] == 0){
        close(pipe_fd[0]);
        dup2(pipe_fd[1], 1);
        close(pipe_fd[1]);
        execvp(prog1[0], prog1);

    }
    if(pid[0] > 0){
        pid[1] = fork();
        if(pid[1] == 0){
            close(pipe_fd[1]);
            dup2(pipe_fd[0], 0);
            close(pipe_fd[0]);

            close(pipe_fd2[0]);
            dup2(pipe_fd2[1], 1);
            close(pipe_fd2[1]);
            execvp(prog2[0], prog2);
        }
        if(pid[1]>0){
            pid[2] = fork();
            if(pid[2] == 0){
                close(pipe_fd2[1]);
                dup2(pipe_fd2[0], 0);
                close(pipe_fd2[0]);

                execvp(prog3[0], prog3);
            }
        }
        close(pipe_fd[0]);
        close(pipe_fd[1]);
        close(pipe_fd2[0]);
        close(pipe_fd2[1]);
        waitpid(pid[1], &status, 0);
    }
    return 0;
}



------解决方案--------------------
你关闭的描述符还是不够,原则就是不用的描述符全部关闭,否则读取管道的那个进程不会结束输入

if(pid[0] == 0)
要关闭pipe_fd2
close(pipe_fd2[0]);
close(pipe_fd2[1]);

if(pid[2] == 0)
要关闭pipe_fd
close(pipe_fd[0]);
close(pipe_fd[1]);