0

I'm trying to read the output of a program launched with execlp into a buffer, this is my code

void do_ls_la_buf() {
    int piped[2];
    if(pipe(piped) == -1) {
        printf("Couldn't initiate pipe\n");
        exit(EXIT_FAILURE);
    }

    if(fork() == 0) {
        close(piped[0]);    // close read end of child
        dup2(piped[1], 1);  // stdout to pipe
        dup2(piped[1], 2);  // stderr to pipe
        close(piped[1]);

        execlp("/usr/bin/ls", "ls", "-la");
    }
    else {
        char buf[1024] = "";
        close(piped[1]);    // close write end of parent

        while(read(piped[0], buf, sizeof(buf))) {
            printf("Read from pipe %d chars: %s\n", strlen(buf), buf);
        }
    }
}

int main {
    do_ls_la_buf();
    wait(NULL);
}

And this is the output I get

Read from pipe 22 chars: ls: cannot access 'H='
Read from pipe 28 chars: : No such file or directory

This does not make any sense to me, since the arguments of execlp are hard-coded.

What's happening?

BaridunDuskhide
  • 107
  • 1
  • 5
  • 2
    You forgot to end it with `NULL`; see some examples. – Ry- Sep 04 '22 at 17:41
  • 1
    Another bug is treating `buf` as a string by passing it to `strlen` and `printf` with `%s`. The `read` function does not null-terminate the data it returns. Since you initialize the buffer to all zeros (which is itself pretty expensive), it will work if `read` happens to read fewer than 1024 bytes and if the data itself doesn't contain any zero bytes, but if it gets the full 1024 bytes, you will overrun `buf` before reaching a null terminator. Don't treat it as a string; instead, use the value returned by `read` to determine exactly how many bytes of it to use. – Nate Eldredge Sep 04 '22 at 18:46
  • 1
    Oh, and using `%d` to print the return value of `strlen` is also incorrect. It returns `size_t`, not `int`, so the proper format specifier is `%zu`. But as mentioned, you should not be using `strlen` here in the first place. – Nate Eldredge Sep 04 '22 at 18:47
  • Thank you both for the insights, I solved the problems I had! – BaridunDuskhide Sep 04 '22 at 20:04

0 Answers0