/* Sample of attaching a file to stdin before execing a command.
   This expects a file name on the command line.
  
   File is opened and duped to file descriptor 0 (stdin).
   Then the sort coammand is exec'd.

*/

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


int main(int argc, char **argv) {
  int fd;

  /* Make sure we got a file name on the command line */
  if (argc<2) {
	printf("Error - you need to specify what file to sort!\n");
	exit(1);
  }

  /* attempt to open the file */
  fd = open(argv[1],O_RDONLY);
  if (fd<0) {
	perror("Fatal Error");
	exit(1);
  }

  /* close STDIN and assign descriptor 0 to same file as fd refers to */
  if (dup2(fd,0)<0) {
	perror("duping error");
	exit(1);
  }

  /* everything is set for the exec - now become sort
     (which will read from stdin). */
  execlp("sort","sort",NULL);

  /* we should never get here! (exec failed) */
  perror("Error execing sort");
  return(0);
}

