#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#define BUFFER_SIZE 512
static void ls() {
int pfd[2];
pid_t pid;
if (pipe(pfd) == -1) {
perror("pipe");
exit(1);
}
pid = fork();
if (pid > 0) {
char buf[BUFFER_SIZE + 1];
int n, status;
close(pfd[1]);
while ((n = read(pfd[0], buf, BUFFER_SIZE)) > 0) {
buf[n + 1] = '\0';
printf("buf: %s\n", buf);
}
close(pfd[0]);
if (waitpid(pid, &status, 0) == -1) {
perror("waitpid");
exit(1);
}
printf("exited, status=%d\n", status);
} else if (pid == 0) {
close(pfd[0]);
if (dup2(pfd[1], STDOUT_FILENO) == -1) {
perror("dup2");
exit(1);
}
if (execlp("ls", "ls", "-la", NULL) == -1) {
perror("execlp");
exit(1);
}
} else {
perror("fork");
exit(1);
}
}
int main() {
ls();
return 0;
}