我正在尝试在 C 中实现多个管道。这是处理管道的函数的主要部分
ProcesscommandwithPipes()
{
............................
for (k=0; k <= num_of_pipes; k++)
   {
      read[k]= -1;
      write[k] = -1;
   }
   //create required number of pipes
    for(j=0; j < num_of_pipes; j++)
    {
       if( pipe(fd) == -1 )
       {
          perror("Pipe failure");
          return;
       }
       read[j+1] = fd[0];
       write[j] = fd[1];
    }
    for(k=0; k<= num_of_pipes; k++)
    {
      pid = fork();
      if(pid < 0 )
      {
         printf("fork failed\n");
      }
      else if (pid == 0)
      {
            if(write[k] != -1)
         {
            if( dup2(write[k],1) == -1){
            perror("dup2 error");
            exit(1);}
         }
        if(read[k] != -1)
         {
            if( dup2(read[k],0) == -1)
            {
              perror("dup2read  error");
              exit(1);
            }
         }
        for (h=0; h<= num_of_pipes;h++)
        {
              close(write[h]);
              close(read[h]);
        }
          if(execvp((const char*)commandArgv[k][0], commandArgv[k]) < 1)
          {
            perror("error");
            exit(1);
          }
        exit(0);
      }
      else
      {
        processid[k] = pid;
        printf("waiting on process:%d\n", processid[k]);
        close(write[k]);
        close(read[k]);
        waitpid(processid[k], &status, 0);
       }
     }
出于某种原因,以下命令可以正常工作 ls|grep tmp|sort
但是以下命令不起作用,尽管它几乎是相同的 cat tmp1.out|grep tmp|sort
(tmp1.out 包含 cur 目录中的文件列表,与 ls 的输出相同)也没有错误消息。但它只是退出而不在屏幕上打印任何内容(尽管最后一个命令的标准输出没有改变)
PS:cat tmp1.out|grep tmp也可以正常工作。
tmp1.out 的内容: a.out 样本 shell.c tmp1.out tmp.out bc
有什么输入吗?