previous | start | next

Redirecting I/O

File descriptors 0, 1, and 2 are in use when a process is created and correspond to standard in, standard out, and standard error respectively.

These are ordinarily keyboard input, terminal output, and terminal output.

This can be changed as in this code fragment:

    1   if (fork() == 0) {
    2     /* set up file descriptor 1 in child process */
    3     close(1);
    4     if (open("/home/me/blob", O_WRONLY) == -1) {
    5       perror("/home/me/blob");
    6       exit(1);
    7     } else {
    8       execlp("/home/me/prog", "prog", "50", (char *) 0);
    9       printf("/home/me/prog: Could not execute.\n");
   10       exit(1);
   11     }
   12   
   13   }
   14    
   15   /* parent continues here */
   16   ...

If the child reads from standard input (e.g. with

      
 scanf or fgets(buf, N, stdin)
   

It will read from the file '/home/me/blob'

A successful open returns the first unused file descriptor: the first (smallest) index in the descriptor table of the first unused entry.



previous | start | next