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

/* Example in which a parent reads output from 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[1], 1);
    close(fd[0]);
    execl("/bin/date", "date", NULL);
  }

  close(fd[1]);

  char buffer[64];
  bzero(buffer,64);
  if (read(fd[0], buffer, 64) == -1) {
    perror("read()");
    exit(1);
  }
  fprintf(stdout,"Output from child: %s",buffer);

  close(fd[0]);

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

  exit(0);
}

