/* catgrep.c -  cat a file passed as parameter and grep with
                the string passed as second parameter.
                It has the same effect as the command
		   cat filename | grep token
 */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
 
int main(int argc, char *argv[]) 
{
  int p[2];  /* pipe established between parent and child */
  pid_t id;  /* value returned by fork operation */
  
  if (argc != 3) {
    printf("Usage: %s filename token\n", argv[0]);
    exit(0);
  }

  if (pipe(p) < 0) {
    perror("Unable to create pipe");
    exit(0);
  }

  if ((id = fork()) == 0) { /* first child */
    close(1);
    dup(p[1]);
    close(p[0]);
    execlp ("/usr/bin/cat", "cat", argv[1], NULL);
  } else if (id < 0) { /* error case */
    perror("Unable to fork");
    exit(0);
  }

  if ((id = fork()) == 0) { /* second child */
    close(0);
    dup(p[0]);
    close(p[1]);
    execlp("/usr/bin/grep", "grep", argv[2], NULL);
  } else if (id < 0) { /* error case */
    perror("Unable to fork");
    exit(0);
  }

  return 0;
}

