Pipe implementation

前端 未结 2 1402
花落未央
花落未央 2020-12-09 21:35

I am trying to implement a linux shell that supports piping. I have already done simple commands, commands running in background, redirections, but piping is still missing.<

相关标签:
2条回答
  • 2020-12-09 21:46

    Look into the pipe() standard library call. This is used to create a pipe. You must of course do part of the work before you fork(), in order for the child process to inherit the file descriptor properly.

    Also note the order of the arguments to dup2():

    int dup2(int oldfd, int newfd);
    

    dup2() makes newfd be the copy of oldfd, closing newfd first if necessary

    0 讨论(0)
  • 2020-12-09 22:03

    You need to replace one child's stdout with the writing end of the pipe, and the other child's stdin with the reading end:

    if (pid == 0)  
    {  
       close(fd[0]); //close read from pipe, in parent
       dup2(fd[1], STDOUT_FILENO); // Replace stdout with the write end of the pipe
       close(fd[1]); // Don't need another copy of the pipe write end hanging about
       execlp("cat", "cat", "names.txt", NULL);
    }
    else
    {
       close(fd[1]); //close write to pipe, in child
       dup2(fd[0], STDIN_FILENO); // Replace stdin with the read end of the pipe
       close(fd[0]); // Don't need another copy of the pipe read end hanging about
       execlp("sort", "sort", NULL);
    } 
    
    0 讨论(0)
提交回复
热议问题