简体   繁体   English

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

[英]Stuffing output of execlp through a pipe and then printing it to console

My current program: 我目前的计划:

 #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;
}

I'd like the parent (else case) to read from the pipe and print the contents to the console. 我希望父(或其他情况)从管道读取并将内容打印到控制台。 I'm not sure where this fails and need some pointers as to what I am doing wrong. 我不确定这个失败的地方,需要一些关于我做错了什么的指示。 Thanks in advance! 提前致谢!

You need to put parenthesis around the assignment in: 您需要在作业中添加括号:

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

The correct statement is: 正确的说法是:

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

Assignment = has lower priority then > , so your original expression was evaluated as: Assignment =优先级低于> ,因此您的原始表达式被评估为:

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

which assigned 1 to bytes_read after each successful read. 每次成功读取后分配1bytes_read

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM