#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>

/* Example in which a parent provides output to a child through
 * a pipe
 */
int main(int argc, char **argv)
{
  pid_t pid;
  int fd[2];

  /* Create a pipe */
  if (pipe(fd) == -1) {
    perror("pipe()");
    exit(1);
  } 

  /* Create a child */
  pid = fork();
  if (pid < 0) {
    perror("fork()");
    exit(1);
  }

  if (!pid) { // child 
    dup2(fd[0], 0);
    close(fd[1]);
    execl("/usr/bin/grep", "grep", "-a", "H", NULL);
//    execl("/sw/bin/tee", "tee", NULL);
  }

  close(fd[0]);

  char buffer[64];

  // Providing the child with input
  sprintf(buffer,"Humpty Dumpty sat on a wall,\n");
  write(fd[1],buffer,strlen(buffer));
  sprintf(buffer,"Humpty Dumpty had a great fall.\n");
  write(fd[1],buffer,1+strlen(buffer));
  sprintf(buffer,"All the king's horses,\n");
  write(fd[1],buffer,1+strlen(buffer));
  sprintf(buffer,"And all the king's men,\n");
  write(fd[1],buffer,1+strlen(buffer));
  sprintf(buffer,"Couldn't put Humpty together again.\n");
  write(fd[1],buffer,1+strlen(buffer));

  close(fd[1]);

  /* waiting for the child */
  int status;
  if (waitpid(pid, &status, 0) == -1) {
    perror("waitpid()");
    exit(1);
  }
  
  exit(0);
}

