使用管道连接shell中的子进程

时间:2015-04-20 22:54:46

标签: linux shell pipe

我试图在我的shell中进行子进程通信。像这样:

ls | ls -l
ls -l | wc -l

问题是,当我做" ls | ls -l"它有效,我得到的是预期的,只有" ls -l"。但是,如果我做" ls -l | wc -l"它只是像节目一样在一个循环中等待。

这是我的代码:

void execute_commands(COMMAND *commlist) {

pid_t process;
COMMAND *first = commlist;
int fd_before[2];
int fd_actual[2];
int status;

while(commlist != NULL) {       

  if(commlist->next != NULL) pipe(fd_actual);

  if ((process = fork()) < 0){ }         // FAILED

  else if (process == 0) {               

    if(first != commlist) {
      dup2(fd_before[0], PIPE_READ);
    }

    if(commlist->next != NULL) {
      dup2(fd_actual[1], PIPE_WRITE);
    }

    /* You can ignore this, it's from input files /*
    if(inputfile != NULL) {  
      int in = open(inputfile, 0);      
      if(in < 0) exit(1);
      dup2(in, 0);
      close(in);
    }
    /* You can ignore this, it's from input files /*
    if(outputfile != NULL) {  
      int out = creat(outputfile, 0644);
      dup2(out, 1);
      close(out);
    }

    if(execvp(commlist->argv[0], commlist->argv)< 0) exit(1);
  }
  else {
    wait(&status);
    commlist = commlist->next;
    fd_before[0] = fd_actual[0];
    fd_before[1] = fd_actual[1];
  }                                    
  close(fd_before[PIPE_READ]);
  close(fd_before[PIPE_WRITE]);
  close(fd_actual[PIPE_READ]);
  close(fd_actual[PIPE_WRITE]);
}

/*wait(&status); Should wait be here, or where it currently is? */

}

-

我有另一个疑问,如果我在子进程中更改我的代码并将其放入:

close(fd_before[PIPE_READ]);
close(fd_before[PIPE_WRITE]);
close(fd_actual[PIPE_READ]);
close(fd_actual[PIPE_WRITE]);

它将关闭我当前的输入和输出,而不是接收或输出任何内容。

但是当我在输入文件&#34;关闭(in);&#34;中执行此操作时,它仍然有效。有什么区别?

1 个答案:

答案 0 :(得分:2)

这适用于ls -l | ls -l,因为该表单中的ls不会读取标准输入,因此即使您忽略正确设置stdin,它也会运行。

对于ls -l | wc -lwc需要stdin来计算行数,并且它没有收到任何输入。

缺少其他一些东西

  • 如果没有PIPE_READ和PIPE_WRITE的定义,我们无法看到您希望出现重复描述符的位置
  • 代码中有未公开的评论,因此显然不完整
  • 在某些时候你需要exec()你的命令(ls,wc,等等)

由于这看起来像是一项任务,我将引导您查看更详细的现有帖子:

Understanding how to connect pipes and wait for them in a custom C shell

UNIX Pipes Between Child Processes

相关问题