多管道实现在C中不起作用

时间:2013-09-05 15:27:29

标签: c linux pipe

我正在尝试在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的输出相同) 没有错误消息。但它只是退出而不在屏幕上打印任何东西(尽管最后一个命令的标准输出没有改变)

P.S: cat tmp1.out | grep tmp 也可以。

tmp1.out的内容: 的a.out 样品 shell.c tmp1.out tmp.out b.c

任何输入?

2 个答案:

答案 0 :(得分:0)

我知道你正在尝试写一个shell,但是你考虑过使用popen吗?

FILE * p = popen(“cat tmp1.out | grep tmp | sort”,“r”);

答案 1 :(得分:0)

问题可能是你在循环中调用waitpid(),因此在第一个进程终止之前你不会启动第二个进程。但是现在第一个可能会挂起,如果达到管道缓冲区大小并且你有一个死锁或一个进程可能被一个破坏的管道杀死。此外,for(k=0; k<= num_of_pipes; k++)对我来说很奇怪,因为它会循环num_of_pipes+1

相关问题