/* This program forks off p processes and hooks them together via
   a chain of pipes.  Each process calls "sed 's/^/PIPE-/'".  The
   first process reads from stdin and the last writes to stdout */

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

main(int argc, char **argv)
{
  int np, i, j;
  int **p;

  if (argc != 2) { fprintf(stderr, "usage: p1 number-of-processes\n"); exit(1); }

  np = atoi(argv[1]);   
  if (np <= 0) {
    fprintf(stderr, "usage: p1 number-of-processes(>0)\n"); 
    exit(1); 
  }

  p = (int **) malloc(sizeof(int *) * (np-1));
  if (p == NULL) { perror("malloc"); exit(1); }

  for (i = 0; i < np-1; i++) {
    p[i] = (int *) malloc(sizeof(int)*2);
    if (p[i] == NULL) { perror("malloc"); exit(1); }
    if (pipe(p[i]) != 0) { perror("pipe"); exit(1); }
  }
   
  for (i = 0; i < np; i++) {
    if (fork() == 0) {
      if (i > 0) dup2(p[i-1][0], 0);
      if (i < np-1) dup2(p[i][1], 1);
      for (j = 0; j < np-1; j++) {
        close(p[j][0]);
        close(p[j][1]);
      }
      execlp("sed", "sed", "s/^/PIPE-/", NULL);
      perror("execlp");
      exit(1);
    }
  }

  for (j = 0; j < np-1; j++) {
    close(p[j][0]);
    close(p[j][1]);
  }
  close(0);
  for (i = 0; i < np; i++) {
    wait(&j);
  }
}

