lsを実行して出力を得る

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