[comp.lang.c] redirecting stdout and stdin

mab718@aplcen.apl.jhu.edu (Bellmore Mark Allen) (07/08/90)

I have seen a few questions reguarding redirection of stdin and
stdout. I apologize if this has been said before. A good 
reference is Advanced UNIX programming by Marc J. Rochkind, 
published by PRENTICE-HALL 1985.
   Here is some sample code:

   #include <stdio.h>
   main()
   {
     int pfd[2];
     char buf[10];

     /* pipe makes pfd[0] for reading and pfd[1] for writing */
     if(pipe(pfd) == -1) {
       perror("pipe");
       exit(-1);
     }
     /* now close stdin to make it available */
     close(0);
     /* dup is GUARANTEED to return the lowest availble fd */
     /* so doing a dup will copy pfd[1] to stdin (fd 1) */
     dup(pfd[0]);
     close(pfd[0]);  /* don't need it anymore */

     /* now reading from stdin will come from the pipe */
     
     strcpy(buf,"TEST PIPE");
     write(fd,buf,9);
     read(0,inbuf,9);
  }

     /* This example is just to show how to redirect stdin */
     /* The same can be done with stdout */