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

/**
 * This program should accept two parameters on the command, a file to copy
 * from and a file to copy to.  Instead of opening and copying the files itself
 * it should create a pipe between the 'from' and 'to' programs to do the
 * copying.  I.e. 'copy source dest' should be the same as typing in the shell:
 * from source | to dest
 * This program should then a) Create a pipe, b) fork a new process, c) exec
 * the from and to programs in their respective processes after redirecting
 * their stdin/stdout to/from the appropriate pipe descriptors.
 * Hint: Remember to close both pipe descriptors in each process after
 *       duplicating them.
 */

int main(int argc, char *argv[])
{
  if (argc < 3) {
    printf("Usage: copy <from> <to>\n");
    return 1;
  }
 
  int pfd[2];
  if (pipe(pfd) < 0) {
    perror("pipe");
    return 1;
  }
  
  int pid = fork();
  if (pid < 0) {
    perror("fork");
    return 1;
  }
  
  if (pid > 0) {
    // Parent will be from <from>, stdout should be replaced with pipe write end
    dup2(pfd[1], STDOUT_FILENO);
    close(pfd[0]);
    execlp("./from", "./from", argv[1], NULL);
    perror("from exec");
    return 1;
  } else {
    // Child will be to <to>, stdin should be replaced with pipe read end
    dup2(pfd[0], STDIN_FILENO);
    close(pfd[1]);
    execlp("./to", "./to", argv[2], NULL);
    perror("to exec");
    return 1;
  }

  return 0;
}
