Using the UNIX Pipe in C
Ed Schaefer
Sidebar
Virtually all UNIX system administrators exploit the power and convenience
offered by pipes when they are working from the command line or writing shell
script. By connecting general purpose filters with pipes, the system administrator
can quickly generate tidy custom reports and analytic tools without the overhead
and housekeeping problems associated with myriad temporary files.
The pipe with all its advantages is also available in C (using the standard
library functions popen() and pipe()), but, typically system administrators
are less inclined to use pipes in their C programs. In this article I'll first
explain how to use popen() from within a C program to read directly from the
output of another program. Then I'll present two more general C functions -
one for reading from the pipe and one for writing to the pipe - and use these
functions to illustrate how pipes are used from within a C program.
The popen() Example
The popen() function allows a C program to spawn a task and then attach itself
to the input or output of that task - which is most commonly a set of pipelined
commands. In its simplest application, the popen() function allows you to connect
a special purpose C program to a sequence of standard commands without writing
a separate piece of shell script. For example, if a special usage report required
you to analyze a sorted list of current users, you could either write a shell
script to generate and sort the list and pipe the results into a special C program
which performs the analysis:
who | sort | analyze
or you could avoid the separate script file by using popen(). The call
input_stream = popen( "who | sort", "r")
executes the pipelined task "who|sort" and connects its output (in
read mode - r) to the pipe input_stream.
|