c - 无法管道三个进程

时间:2015-02-26 00:07:21

标签: c process pipe

我一直在尝试在c中实现以下命令: cat / etc / passwd | cut -f1 -d:|排序

这是我到目前为止所获得的代码。第一个管道正常工作,但第二个管道似乎根本无法工作。

我一遍又一遍地检查了代码,但看不出有什么不妥。任何人都可以提出一个可以解决我的问题的建议吗?

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

int main(void)
    {
        int pipe_A[2];
        int pipe_B[2];

        pipe(pipe_A);
        pipe(pipe_B);

        pid_t pid_A, pid_B, pid_C;

        if( !(pid_A = fork()) ) {
            close(1);       /* close normal stdout */
            dup(pipe_A[1]);   /* make stdout same as pipe_A[1] */
            close(pipe_A[0]); /* we don't need this */
            execlp("/bin/cat", "cat", "/etc/passwd" ,  NULL);
        }

        if( !(pid_B = fork()) ) {
            close(0);       /* close normal stdin */
            dup(pipe_A[0]);   /* make stdin same as pipe_A[0] */
            close(pipe_A[1]); /* we don't need this */

            close(1);   /* close normal stdout */
            dup(pipe_B[1]);   /* make stdout same as pipe_B[1] */
            close(pipe_B[0]); /* we don't need this */
            execlp("/usr/bin/cut", "cut", "-f1", "-d:", NULL);
       }

       if( !(pid_C = fork()) ) {
            close(0);       /* close normal stdin */
            dup(pipe_B[0]);   /* make stdin same as pipe_B[0] */
            close(pipe_B[1]); /* we don't need this */
            execlp("/usr/bin/sort", "sort", NULL);
       }

    return 0;
}

谢谢。

1 个答案:

答案 0 :(得分:0)

问题是你正在泄漏开放的FD。请注意,每次调用fork时,所有打开的管道都会被子进程继承,但具有复制FD的管道无法正常工作。

例如,cat继承了pipe_B的读取和写入FD。同样,sort继承了pipe_A的两个FD。

正确的方法是(但我建议改为使用dup2()):

int main(void)
{
    int pipe_A[2];
    int pipe_B[2];
    pid_t pid_A, pid_B, pid_C;

    pipe(pipe_A);

    if( !(pid_A = fork()) ) {
        close(pipe_A[0]); // A-read not needed here

        close(1);
        dup(pipe_A[1]);
        close(pipe_A[1]); //do not pass A-write twice

        execlp("/bin/cat", "cat", "/etc/passwd" ,  NULL);
    }

    close(pipe_A[1]); // A-write not needed anymore

    pipe(pipe_B); //do not create this pipe until needed

    if( !(pid_B = fork()) ) {
        close(pipe_B[0]); // B-read not needed here

        close(0);
        dup(pipe_A[0]);
        close(pipe_A[0]); //do not pass A-read twice


        close(1);
        dup(pipe_B[1]);
        close(pipe_B[1]); //do not pass B-write twice

        execlp("/usr/bin/cut", "cut", "-f1", "-d:", NULL);
   }
   close(pipe_A[0]); // A-read not needed anymore
   close(pipe_B[1]); // B-write not needed anymore

   if( !(pid_C = fork()) ) {

        close(0);
        dup(pipe_B[0]);
        close(pipe_B[0]); // do not pass B-read twice

        execlp("/usr/bin/sort", "sort", NULL);
   }
   close(pipe_B[0]); // B-read not needed anymore
   return 0;
}

如果你分析我的代码(如果我写得正确的话),假设父进程只有FD 0,1和2,那么每个execlp()就会得到3个FD,0,1和2。