CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Inter-process communication using pipes in C

Contemporary systems provide a system call, imaginatively named pipe(), to create a unidirectional communication buffer.

  • Within the operating system kernel, a pipe is a vector of memory, typically 4096 bytes long

  • From within a C program, a pipe is represented as an array of two integer file-descriptors. Writing data to array[0] adds the data to the pipe, and reading from array[1] removes that data.

    
    #include  <unistd.h>
    
    int  thepipe[2];
    char data[1024];
    int  datasize, nbytes;
    
    if(pipe(thepipe) != 0) {
        perror("cannot create pipe");
        exit(EXIT_FAILURE);
    }
    
    datasize = ...
    nbytes   = write( thepipe[0], data, datasize);       // write to the pipe
    
    nbytes   =  read( thepipe[1], data, sizeof(data));   // read from the pipe
    

Pipes have a finite size, typically 4096 bytes, and their typical use affects the scheduling of processes connected by the same pipe:

  • A newly created pipe is empty.
  • Data written to the writing end is added to the pipe.
  • If a process tries to write more data than will fit in the pipe, that writing process is blocked until space becomes available.
  • Data read from the reading end is removed from the pipe.
  • If a process tries to read more data than is held in the pipe (including if the pipe is empty) then that reading process is blocked until data becomes available.
  • A pair of processes writing and reading using the same pipe, 'cause' those processes to (roughly) alternate their execution.

 


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