CITS2002 Systems Programming  
prev
CITS2002 CITS2002 schedule  

Duplicating file-descriptors using dup2()

Of course it's very unusual for a child process to keep running the 'same code' as its parent process.

More typically, the child process will call execl() to commence the execution of another program. Even though a new program commences, the process's open file-descriptors remain open.

Moreover, if the new program (such as sort) is a filter expecting to receive its input via its standard-input stream (file descriptor 0), then we must perform to 'plumbing' with the dup2() system-call to arrange our descriptors:


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

void communicate(void)
{
    ....
    switch ( fork() ) {
    ....

//  CHILD PROCESS RUNS sort, READING ITS stdin FROM THE PIPE
    case 0  :                     // new child process
        close( thepipe[1] );      // child will never write to pipe
        dup2(  thepipe[0], 0);    // duplicate/clone the reading end's descriptor and stdin 
        close( thepipe[0] );      // close the reading end's descriptor

        // child may now read from its stdin (fd=0)

        execl("/usr/bin/sort", "sort", NULL);   // execute a new (filter) program
        perror("/usr/bin/sort");

        exit(EXIT_FAILURE);
        break;

    default :                     // parent process
        close( thepipe[0] );      // parent will never read from pipe
        dup2(  thepipe[1], 1);    // duplicate/clone the writing end's descriptor and stdout 
        close( thepipe[1] );      // close the writing end's descriptor

        // parent may now write to its stdout (fd=1)
        ....
        break;
    }
}

 


CITS2002 Systems Programming, Lecture 18, p12, 2nd October 2023.