Unix pipes: example 1

/*  Chaotic Actors
    This toy program is an example of a
    three way pipe in action.  The story
    behind the game is that there are
    three actors sitting in a circle 
    who are all hard of hearing
    in their one ear (say the right one).  
    Each actor knows the lines of the actor
    to her/his right.  They rehearse their
    lines by whispering the lines to the
    actor on their right (via a pipe).  
    Upon hear a line whispered the actor 
    then states (to stdout) the line heard.
*/   

#include 
#define MAXBUFSIZE 1024
#define MAXLINE 32

/* actors lines */
char lines[3][2][MAXLINE] = {{"That's life.\n", "How much is it?\n"}, 
			     {"What's life?\n", "Thirty-five cents.\n"}, 
			     {"A game.\n", "Oh, that's too much!!\n"}};

int act(int , int , int );

main()  {
  int pid, pipefds[3][2];
	
  /* parent opens three pipes */
  if(pipe(pipefds[0]) < 0)  {
    perror("actor");
    exit(1);
  }
  if(pipe(pipefds[1]) < 0)  {
    perror("actor");
    exit(1);
  }
  /* fork child process actor 2 from actor 1 */ 
  if((pid = fork()) < 0) {
    perror("actor");
    exit(1);
  }
  if(pid == 0) {
    /* neither actor2 nor actor3 use the following pipes so close them */
    close(pipefds[0][0]);
    close(pipefds[1][1]);
    if(pipe(pipefds[2]) < 0)  {
      perror("actor");
      exit(1);
    } 
    /* fork child process actor 3 from actor 2 */ 
    if((pid = fork()) < 0) {
      perror("actor");
      exit(1);
    }
    /* actor 3 */
    if(pid == 0) {
      close(pipefds[1][0]);      
      close(pipefds[2][1]);
      act(3, pipefds[2][0], pipefds[0][1]);
      exit(0);
    }
    /* actor 2 */
    close(pipefds[0][1]);      
    close(pipefds[2][0]);
    act(2, pipefds[1][0], pipefds[2][1]);
    exit(0);
  }
  /* actor1 */
  close(pipefds[0][1]);      
  close(pipefds[1][0]);
  act(1, pipefds[0][0], pipefds[1][1]);  
  exit(0);
}

/* act - rehearse the play (forever)
   actorid - identifies which actor is speaking 
   fdin    - pipe to next actor
   fdout   - pipe from previous actor
*/ 

act(int actorid, int fdin, int fdout) {
  int i;
  char *buffer[MAXBUFSIZE];
  
  while(1) {
    for( i=0; i < 2; i ++) {
      write(fdout, lines[actorid - 1][i], sizeof(lines[actorid - 1][i]));
      fflush(stdout);
      read(fdin, buffer, MAXBUFSIZE);
      printf("actor%d states: %s", actorid, buffer);
      fflush(stdout);
      sleep(1);
    }
  }
}


Send email to cs153@csif.cs.ucdavis.edu.

Department of Computer Science
University of California at Davis
Davis, CA 95616-8562



Page last modified on 2/5/97