UNIX管道 - 三道工序之间的管道

UNIX管道 - 三道工序之间的管道

问题描述:

我创建一个小程序,它包含三个过程;源处理,滤波处理和一个接收器的过程。震源过程的标准输出重定向到过滤过程的标准输入,并且过滤器进程的标准输出重定向到水槽进程的标准输入。

I'm creating a small program which contains three processes; a source process, a filter process and a sink process. The stdout of the source process is redirected to the stdin of the filter process, and the filter process' stdout is redirected to the sink process' stdin.

我的问题是,没有输出打印从水槽工艺到标准输出。可在code以下的小片段任你看这个问题?

My problem is that no output is printed to stdout from the sink process. Can any of you see the problem in the following tiny snippet of code?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>


int main(int argc, char** argv)
{
     // Pipes
     // pipe1 is from source to filter, pipe2 is from filter to sink
     int pipe1[2], pipe2[2];

     // Create pipes
     if (pipe(pipe1) < 0 || pipe(pipe2) < 0)
     {
          perror("Creating pipes failed!");
     }

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

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

          execlp("ls", "ls", NULL);
          exit(0);
     }
     else
     {
          if (fork() == 0)
          {
               close(0);
               dup(pipe1[0]);
               close(pipe1[1]);

               close(1);
               dup(pipe2[1]);
               close(pipe2[0]);

               execlp("sort", "sort", NULL);
               exit(0);
          }
          else
          {
               if (fork() == 0)
               {

                    close(0);
                    dup(pipe2[0]);

                    execlp("more", "more", NULL);
                    exit(0);
               }
          }
     }


     wait(NULL);
     printf("Done.\n");

     return 0;
}

BR

一些简单的方法来为您的方案做管道:

Some easy way to do pipes for your scenario:

char cmd[MAX_LEN];
sprintf(cmd, "%s | %s | %s", app1, app2, app3); //app123 holds app name + args
system(cmd);

如果你想获取的最后一个应用程序的输出,使用的popen:

if you want to capture the output of the last app, use popen:

FILE pPipe = popen(cmd, "rt"); /* same access flag as fopen()*/
while (NULL != fget(buf, buf_len, pPipe)) {
    // do something with the read line in 'buf'
}