CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Inter-process communication using pipes in C, continued

While the previous code will work (a single process can write-and-read with itself!), the true power of pipes obviously comes when two processes communicate using the same pipe.

  • But, if a pipe is an array of two integers, how do two processes access that same array?
The solution requires that processes sharing a pipe must be 'related'. In the following example, a (parent) process creates a pipe, forks a child process, and both processes now have access to the same pair of file descriptors:


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

void communicate(void)
{
    int>  thepipe[2]
    char data[1024];
    int  datasize, nbytes;

    if(pipe(thepipe) != 0) {
        perror("cannot create pipe");
        exit(EXIT_FAILURE);
    }

// fork()ing THE PROCESS WILL DUPLICATE ITS DATA, INCLUDING THE pipe'S TWO FILE-DESCRIPTORS

    switch ( fork() ) {
    case -1 :
        printf("fork() failed\n"); // process creation failed
        exit(EXIT_FAILURE);
        break;

    case 0:                       // new child process
        close( thepipe[0] );      // child will never write to pipe
        nbytes = read( thepipe[1], data, sizeof(data));   // read from the pipe
        ....
        close( thepipe[1] );

        exit(EXIT_SUCCESS);
        break;

    default:                      // original parent process
        close( thepipe[1] );      // parent will never read from pipe
        datasize = ...
        nbytes   = write( thepipe[0], data, datasize);    // write to the pipe
        ....
        close( thepipe[0] );
        break;
    }
}

 


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