Implementing pipe in C

前端 未结 2 1831
情书的邮戳
情书的邮戳 2020-12-03 11:57

I am trying to implement pipe in C. eg - $ ls | wc | wc

I have written the following code -

#include
#include

        
相关标签:
2条回答
  • 2020-12-03 12:17

    This does virtually no error checking, but why so complicated?

    int main (int argc, char ** argv) {
        int i;
    
        for( i=1; i<argc-1; i++)
        {
            int pd[2];
            pipe(pd);
    
            if (!fork()) {
                dup2(pd[1], 1); // remap output back to parent
                execlp(argv[i], argv[i], NULL);
                perror("exec");
                abort();
            }
    
            // remap output from previous child to input
            dup2(pd[0], 0);
            close(pd[1]);
        }
    
        execlp(argv[i], argv[i], NULL);
        perror("exec");
        abort();
    }
    
    0 讨论(0)
  • 2020-12-03 12:18

    If your are still interested in why your source didn't work (Sergey's solution is better anyway):

    The problem is not closing the write side of fd_1 in the parent process. Thus both argv[1] and parent have been writers to that pipe and that caused the confusion. Please don't ask for more details (esp. why the prob doesn't occur if you use only one pipe) but your original source will run with tree processes if you just add a close( fd_1[1] ); after the first call of run_cmd()

    0 讨论(0)
提交回复
热议问题