通过管道填充execlp的输出,然后将其打印到控制台

时间:2014-03-01 17:59:34

标签: c linux fork pipe

我目前的计划:

 #include <stdio.h>
 #include <unistd.h>
 #include <sys/wait.h>
 #ifndef STD_IN
 #define STD_IN 0
 #endif
 #ifndef STD_OUT
 #define STD_OUT 1
 #endif

int main(int argc, char *argv[]) {
    int mypipe[2];
    int pid;
    if (pipe(mypipe)) return -1;
    if ((pid = fork()) == -1) return -1;
    else if (pid == 0) {
        //child puts stuff in pipe
        close(mypipe[0]);
        dup2(mypipe[1], STD_OUT);
        execlp("ls", "ls", "-l", NULL);
        close(mypipe[1]);
    } else {
        //parent reads and prints from pipe
        char buf[1024];
        int bytes_read;
        close(mypipe[1]);
        while (bytes_read = read(mypipe[0], buf, 1024) > 0) {
            write(STD_OUT, buf, bytes_read); //write from buf to STD_OUT
        }
        wait(NULL);
        close(mypipe[0]);
    }
    return 0;
}

我希望父(或其他情况)从管道读取并将内容打印到控制台。我不确定这个失败的地方,需要一些关于我做错了什么的指示。提前谢谢!

1 个答案:

答案 0 :(得分:2)

您需要在作业中添加括号:

while (bytes_read = read(mypipe[0], buf, 1024) > 0) {

正确的陈述是:

while ((bytes_read = read(mypipe[0], buf, 1024)) > 0) {

作业=的优先级低于>,因此您的原始表达式评估为:

while (bytes_read = (read(mypipe[0], buf, 1024) > 0)) {

在每次成功阅读后将1分配给bytes_read