next up previous
Next: Starting and Resuming Up: Command Interpreters Previous: Input/Output Redirection

Pipes

A command interpreter may also bind the standard input of a process to the standard output of another process. This facility is useful for creating new applications by combining together existing applications. Thus a user may execute the command:

ls | more
to get a paged listing of a directory. This command is more useful than the sequence of commands:
ls > temp
more < temp
rm temp
The latter scheme is more longwinded. Moreover, it results in the unnecessary creation of a temporary file on disk. Finally, it reduces the concurrency and does not allow lazy evaluation.

How are pipes set up? The example command

ls | more
illustrates the mechanism. The shell calls the procedure pipe, which creates a pipe and returns two descriptors i and o for reading from and writing to the pipe. It then forks two processes p and q for executing the ls and more programs respectively. Process p, before execing the file ls calls dup2 (o, 1) to duplicate the descriptor o onto its standard output descriptor, and then closes i and o. Process q does a similar set of steps to connect its standard input to i.

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