Search code examples
cparent-childpipeline

Pipeline Communication between Child Process and Parent Process using pipe()


I am trying to set up a pipeline to communicate between a child process and a parent process using pipe(). I read some posts on stackoverflow some use the dup() and dup2() functions. Can someone explain what is the use of these functions in this scenario?


Solution

  • You could use dup2 to redirect the stdin and stdout of a child and parent process respectively to send messages through a pipe used with file descriptors created with the instruction pipe. To illustrate its functionality in a more concrete way, here is a detailed example on how to do so.

    #include <unistd.h>
    #include <stdio.h>
    #define READ 0
    #define WRITE 1
    int main (int argc, char * argv [ ] )
    { 
        int fd[2];
        pipe(fd); // creating an unnamed pipe
        if (fork() !=0)
        { 
            close(fd[READ]); // Parent close the reading descriptor
            dup2(fd[WRITE], 1); // copy fd[WRITE]] in the descriptor 1 (stdout)
            close (fd[WRITE]); // closing the writing descriptor, not needed anymore because of stdout
            if(execlp(argv[1], argv[1], NULL) ==-1) // execute the program writer passed as an argument to myprog
                perror("error in execlp");
        }
        else // child process (reader)
        { 
            // closing unused writing descriptor
            close(fd[WRITE]);
            // copy fd[READ] in descriptor 0 (stdin)
            dup2(fd[READ],0);
            close (fd[READ]); // closing reading descriptor, not needed anymore because of stdin
            // execute reading command
            if(execlp(argv[2], argv[2], NULL) == -1) // Execute the reader passed as an argument to myprog
                perror("connect");
        }
        return 0 ;
    }
    

    With that, every messages sent by the parent process through the standard output will be redirected to the standard input of the child process. For example, when executing the command myprog who wc (with the code shown above), it behaves just like doing who | wc in the terminal. You can see my parent process who will send messages to wc through the standard output.

    As it is for the difference between dup and dup2. You can check out this link.