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?