使用pipe和dup2重定向stdin / stdout时管道损坏

时间:2018-03-31 20:48:49

标签: c unix

我想重现输入shell时会发生什么:

ps eaux | grep "^USERNAME" | wc -l

(其中USERNAME$USER env var或我作为程序参数提供的任何内容。)

不幸的是,这不起作用:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

int main(int argc, char * argv[]) {
    int i;
    int pipefd1[2];
    int pipefd2[2];
    pipe(pipefd1);
    pipe(pipefd2);



    for (i=0; i<2; i++) {


        switch (fork()) {
            case -1:
                perror("Fork error");
            case 0:
                pipe(pipefd2);
                if (i == 0) { // Execution of grep

                    char grepArg[1024];

                    if (argc == 2) {
                        sprintf(grepArg, "\"^%s\"", argv[1]);
                    } else {
                        sprintf(grepArg, "\"^%s\"", getenv("USER"));
                    }

                    close(pipefd1[1]);
                    close(pipefd2[0]);

                    dup2(pipefd1[0], STDIN_FILENO);
                    dup2(pipefd2[1], STDOUT_FILENO);

                    close(pipefd1[0]);
                    close(pipefd2[1]);

                    execlp("cat", "cat", NULL);

                } else { // Execution of wc
                    close(pipefd1[0]);
                    close(pipefd1[1]);
                    close(pipefd2[1]);

                    dup2(pipefd2[0], STDIN_FILENO);
                    close(pipefd2[0]);
                    execlp("wc", "wc", "-l", NULL);
                }

        }

    }
    close(pipefd1[0]);
    dup2(pipefd1[1], STDOUT_FILENO);
    close(pipefd1[1]);
    execlp("ps", "ps", "eaux", NULL);
    return 0;
}

这是错误:

       0
cat: stdout: Broken pipe

出了什么问题?

谢谢

0 个答案:

没有答案