It is often easier to use a program written
by someone else than to invent one's own.
This section describes how to
execute a program from within another.
The easiest way to execute a program from another
the standard library routine
takes one argument, a command string exactly as typed
(except for the newline at the end)
For instance, to time-stamp the output of a program,
If the command string has to be built from pieces,
the in-memory formatting capabilities of
normally buffer their input;
terminal I/O will not be properly synchronized unless
this buffering is defeated.
Low-Level Process Creation \(em Execl and Execv
If you're not using the standard library,
or if you need finer control over what
you will have to construct calls to other programs
using the more primitive routines that the standard
The most basic operation is to execute another program
To print the date as the last action of a running program,
execl("/bin/date", "date", NULL);
of the command; you have to know where it is found
The second argument is conventionally
(that is, the last component of the file name),
but this is seldom used except as a place-holder.
If the command takes arguments, they are strung out after
the end of the list is marked by a
overlays the existing program with
return to the original program.
a program might fall into two or more phases
that communicate only through temporary files.
Here it is natural to make the second pass
The one exception to the rule that the original program never gets control
back occurs when there is an error, for example if the file can't be found
execl("/bin/date", "date", NULL);
execl("/usr/bin/date", "date", NULL);
fprintf(stderr, "Someone stole 'date'\n");
is useful when you don't know in advance how many arguments there are going to be.
is an array of pointers to the arguments;
the last pointer in the array must be
can tell where the list ends.
is the file in which the program is found, and
is the name of the program.
(This arrangement is identical to the
array for program arguments.)
Neither of these routines provides the niceties of normal command execution.
There is no automatic search of multiple directories \(em
you have to know precisely where the command is located.
Nor do you get the expansion of metacharacters like
which then does all the work.
that contains the complete command as it would have been typed
at the terminal, then say
execl("/bin/sh", "sh", "-c", commandline, NULL);
The shell is assumed to be at a fixed place,
says to treat the next argument
as a whole command line, so it does just what you want.
The only problem is in constructing the right information
Control of Processes \(em Fork and Wait
So far what we've talked about isn't really all that useful by itself.
Now we will show how to regain control after running
Since these routines simply overlay the new program on the old one,
to save the old one requires that it first be split into
one of these can be overlaid, while the other waits for the new,
overlaying program to finish.
The splitting is done by a routine called
splits the program into two copies, both of which continue to run.
The only difference between the two is the value of
In one of these processes (the ``child''),
is non-zero; it is the process number of the child.
Thus the basic way to call, and return from,
execl("/bin/sh", "sh", "-c", cmd, NULL); /* in child */
And in fact, except for handling errors, this is sufficient.
makes two copies of the program.
In the child, the value returned by
More often, the parent wants to wait for the child to terminate
before continuing itself.
This still doesn't handle any abnormal conditions, such as a failure
or the possibility that there might be more than one child running simultaneously.
of the terminated child, if you want to check it against the value
Finally, this fragment doesn't deal with any
funny behavior on the part of the child
are the heart of the standard library's
which we'll show in a moment.
encodes in its low-order eight bits
the system's idea of the child's termination status;
it is 0 for normal termination and non-zero to indicate
various kinds of problems.
The next higher eight bits are taken from the argument
which caused a normal termination of the child process.
It is good coding practice
for all programs to return meaningful
When a program is called by the shell,
the three file descriptors
0, 1, and 2 are set up pointing at the right files,
and all other possible file descriptors
When this program calls another one,
correct etiquette suggests making sure the same conditions
calls affects open files in any way.
If the parent is buffering output
that must come out before output from the child,
the parent must flush its buffers
if a caller buffers an input stream,
the called program will lose any information
that has been read by the caller.
is an I/O channel intended for use
between two cooperating processes:
one process writes into the pipe,
The system looks after buffering the data and synchronizing
Most pipes are created by the shell,
which connects the standard output of
Sometimes, however, it is most convenient
for a process to set up its own plumbing;
in this section, we will illustrate how
the pipe connection is established and used.
Since a pipe is used for both reading and writing,
two file descriptors are returned;
the actual usage is like this:
/* there was an error ... */
is an array of two file descriptors, where
is the read side of the pipe and
calls just like any other file descriptors.
If a process reads a pipe which is empty,
it will wait until data arrives;
if a process writes into a pipe which
is too full, it will wait until the pipe empties somewhat.
If the write side of the pipe is closed,
will encounter end of file.
To illustrate the use of pipes in a realistic setting,
let us write a function called
and returns a file descriptor that will either
read or write that process, according to
fout = popen("pr", WRITE);
creates a process that executes
calls using the file descriptor
will send their data to that process
to create two copies of itself.
The child decides whether it is supposed to read or write,
closes the other side of the pipe,
then calls the shell (via
to run the desired process.
The parent likewise closes the end of the pipe it does not use.
These closes are necessary to make end-of-file tests work properly.
For example, if a child that intends to read
fails to close the write end of the pipe, it will never
see the end of the pipe file, just because there is one writer
#define tst(a, b) (mode == READ ? (b) : (a))
if ((popen_pid = fork()) == 0) {
close(tst(p[WRITE], p[READ]));
dup(tst(p[READ], p[WRITE]));
close(tst(p[READ], p[WRITE]));
execl("/bin/sh", "sh", "-c", cmd, 0);
_exit(1); /* disaster has occurred if we get here */
close(tst(p[READ], p[WRITE]));
return(tst(p[WRITE], p[READ]));
that the task is to create a child process that will read data from the parent.
closes the write side of the pipe,
leaving the read side open.
dup(tst(p[READ], p[WRITE]));
are the conventional way to associate the pipe descriptor
with the standard input of the child.
closes file descriptor 0,
that is, the standard input.
returns a duplicate of an already open file descriptor.
File descriptors are assigned in increasing order
and the first available one is returned,
is to copy the file descriptor for the pipe (read side)
thus the read side of the pipe becomes the standard input.
(Yes, this is a bit tricky, but it's a standard idiom.)
Finally, the old read side of the pipe is closed.
A similar sequence of operations takes place
when the child process is supposed to write
from the parent instead of reading.
You may find it a useful exercise to step through that case.
The job is not quite done,
for we still need a function
to close the pipe created by
The main reason for using a separate function rather than
is that it is desirable to wait for the termination of the child process.
First, the return value from
indicates whether the process succeeded.
Equally important when a process creates several children
is that only a bounded number of unwaited-for children
can exist, even if some of them have terminated;
pclose(fd) /* close pipe fd */
register r, (*hstat)(), (*istat)(), (*qstat)();
istat = signal(SIGINT, SIG_IGN);
qstat = signal(SIGQUIT, SIG_IGN);
hstat = signal(SIGHUP, SIG_IGN);
while ((r = wait(&status)) != popen_pid && r != -1);
make sure that no interrupts, etc.,
interfere with the waiting process;
this is the topic of the next section.
The routine as written has the limitation that only one pipe may
be open at once, because of the single shared variable
it really should be an array indexed by file descriptor.
function, with slightly different arguments and return value is available
as part of the standard I/O library discussed below.
As currently written, it shares the same limitation.