Balz Guenat
Balz Guenat

Reputation: 1711

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!

Upvotes: 0

Views: 114

Answers (1)

Marian
Marian

Reputation: 7482

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:

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

which assigned 1 to bytes_read after each successful read.

Upvotes: 2

Related Questions