将一个子进程的输出管道化为另一个子进程的输入

时间:2018-04-02 04:34:56

标签: c pipe fork posix

我试图用排序运行ls -l 所以sort可以应用于ls -l <​​br/> 但是当我运行它时它并没有给出相同的输出 作为ls -l |分类 我不确定为什么我理解管道,笨蛋,叉子,有点关闭但仍然困惑 如何应用它们来完成这项工作

  int pipe1[2];
  // will hold the ids of our forks
  pid_t pid1;
  // will hold the ids of our forks
  pid_t pid2;

  pipe(pipe1);

  // call our child process
  pid1 = fork();

  if (pid1 == 0)
  {
    // dealocate the 1 of
    close(1);
    // duplicate the write end
    dup(pipe1[1]);
    // close the read end
    close(pipe1[0]);
    // close the write end
    close(pipe1[1]);

    printf("child1 executing ls \n");
    execl("/bin/ls", "ls", 0, 0);
    perror("execl error");
  }
  else
  {
    wait(&pid1);

    pid2 = fork();

    if (pid2 == 0)
    {
      close(0);
      dup(pipe1[0]);
      close(pipe1[0]);
      close(pipe1[1]);

      printf("child2 executing sort \n");
      execl("/bin/sort", "sort",0, 0);
      perror("execl error");
    }
    else
    {
      wait(0); //wait for children
    }
  }
}

1 个答案:

答案 0 :(得分:0)

将下面添加到else {[here] wait(0); }

close(pipe1[0]);
close(pipe1[1]) ;