POPEN(3S)

NAME
popen, pclose - open or close a pipe (for I/O) from or to a process

SYNOPSIS
#include <stdio.h>

FILE *popen(command, type)
char *command, *type;

pclose(stream)
FILE *stream;

DESCRIPTION
The arguments to popen() are pointers to null-terminated strings containing, respectively, a shell command line and an I/O mode, either r for reading or w for writing. popen() creates a pipe between the calling process and the command to be executed. The value returned is a stream pointer such that one can write to the standard input of the command, if the I/O mode is w, by writing to the file stream; and one can read from the standard output of the command, if the I/O mode is r, by reading from the file stream.

A stream opened by popen() should be closed by pclose(), which waits for the associated process to terminate and returns the exit status of the command.

Because open files are shared, a type r command may be used as an input filter, reading its standard input (which is also the standard output of the process doing the popen()) and providing filtered input on the stream, and a type w command may be used as an output filter, reading a stream of output written to the stream process doing the popen() and further filtering it and writing it to its standard output (which is also the standard input of the process doing the popen()).

popen() always calls sh(1), never csh(1).

SEE ALSO
csh(1), sh(1), pipe(2V), wait(2V), fclose(3V), fopen(3V), system(3)

DIAGNOSTICS

popen() returns a NULL pointer if the pipe or process cannot be created, or if it cannot allocate as much memory as it needs.

pclose() returns -1 if stream is not associated with a `popened' command.

BUGS

If the original and `popened' processes concurrently read or write a common file, neither should use buffered I/O, because the buffering gets all mixed up. Similar problems with an output filter may be forestalled by careful buffer flushing, for instance, with fflush(); see fclose(3V).