next up previous
Next: Pipes Up: Command Interpreters Previous: Macro Substitution

Input/Output Redirection

The input source and output destination of a program must be bound at some point; the logical name used by the program must be associated with a physical name of a file or device. A simple, but inflexible, scheme is to do the binding at compile time. A more flexible scheme is to do so at invocation time, thus providing the user control over the binding. Some command interpreters provide such binding. For instance the Unix C shell processes the command:

sort
by binding the logical input and output to the input and output streams of the terminal, the command
sort < data.in
by binding the input to the file `data.in' and the output to the terminal, and the command,
sort < data.in > data.out
by binding the input to the file `data.in' and the output to `data.out'.

How does the command interpreter do the binding of logical input and output? Let us first consider input. In Unix, the child process, before executing the desired object file, checks if the input is to be redirected to some file in_file. If so, it executes the following code:

i <- open (in_file);
dup2 (i, 0); (* 0 is standard input *)
close (i)
which opens in_file, then copies the contents of the ith entry in the processes' file table into the 0th entry, and finally removes the ith entry. After execution of this code, the descriptor for standard input points to in_file. Similarly, standard output can be redirected to some file.

Prasun Dewan
Thu Mar 28 12:06:42 EST 2002