
/* redirect.c This program expects as parameter the name of a file
 * in the current directory. It does a fork, redirects input to
 * come from the file, and then does an exec on a program (the command cat) that 
 * copies from standard input to standard output.
 */

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

int main(int argc, char *argv[]) {
   pid_t pid;
   int fid;

   if(argc!=2){
     printf("Usage: %s filename\n",argv[0]);
     exit(0);
   }
   if((pid=fork()) < 0){
     perror("fork");
     exit(0);
   }else if (pid==0){
     if((fid=open(argv[1],O_RDONLY,0)) < 0){
       perror("open");
       exit(0);
     }
     if (fid!=STDIN_FILENO)
       /* set STDIN_FILENO to denote the file associated with fid */
       if (dup2(fid, STDIN_FILENO)!=STDIN_FILENO){
       perror("dup2");
       exit(0);
       }
     if(execvp("cat", 0) < 0){ /* execute the cat program */
       perror("execvp");
       exit(0);
     }     
   }
   return 0;
}

