

#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <sys/types.h>

void die(char *msg) {
  perror(msg);
  exit(1);
}

int main(void) {
  pid_t pid;
  int pipe_fd[2];

  if (pipe(pipe_fd) != 0) die("pipe");
   
  pid = fork();
  if (pid == -1) die("fork");
  if (pid) { 
    char c;
    /* I'm the parent */
    close(pipe_fd[0]);           /* close pipe reading end */
    while (read(0, &c, 1) > 0) 
      write(pipe_fd[1], &c, 1);
    fprintf(stderr, "Parent: Got EOF on stdin\n");
    sleep(1);

    fprintf(stderr, "Parent: Closing pipe\n");
    close(pipe_fd[1]);
    sleep(1);

    fprintf(stderr, "Parent: Waiting for child to exit\n");
    wait(NULL);

    sleep(1);
    fprintf(stderr, "Parent: Child exited; exiting now\n");
    return 0;
  } else {
    /* I'm the child */
    char c[2] = "x*";
    close(pipe_fd[1]);           /* close pipe writing end */
    while (read(pipe_fd[0], &c, 1) > 0) {
      write(1, &c, 2);
      sleep(1);
    }
    fprintf(stderr, "Child:  Got EOF on pipe; exiting in 2 seconds\n");
    sleep(2);
    return 0;
  }
}


