popen(3) CLIX popen(3)
NAME
popen, pclose - Initiates a pipe to/from a process
LIBRARY
Standard C Library (libc.a)
SYNOPSIS
#include <stdio.h>
FILE *popen(
char *command ,
char *type );
int pclose(
FILE *stream );
PARAMETERS
command A shell command line
type A character flag representing a read or write mode
stream A stream pointer
DESCRIPTION
The popen() function creates a pipe between the calling program and the
command to be executed. The arguments to popen() are pointers to null-
terminated strings. The command parameter consists of a shell command
line. The parameter type is an I/O mode, either r for reading or w for
writing. The value returned is a stream pointer such that one can write
to stdin of the command by writing to the file stream, if the I/O mode is
w. Also, if the I/O mode is r, one can read from stdout of the command 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.
Since open files are shared, a type r command may be used as an input
filter, and a type w may be used as an output filter.
EXAMPLE
A typical call may be:
char *cmd = "ls *.c";
FILE *ptr;
2/94 - Intergraph Corporation 1
popen(3) CLIX popen(3)
if ((ptr = popen(cmd, "r")) != NULL)
while (fgets(buf, n, ptr) != NULL)
(void) printf("%s",buf);
This example displays, in stdout (see stdio), all the filenames in the
current directory having a .c suffix.
CAUTIONS
If the original and the popen()ed processes read() or write() a common
file concurrently, neither should use buffered I/O. This causes a
buffering mix-up. Prevent output filter problems by using careful buffer
flushing; for example, using fflush(). Also, refer to fclose() .
RETURN VALUES
If files or processes cannot be created, the popen() returns a NULL
pointer. If stream is not associated with a popen()ed command, the
pclose() returns -1.
RELATED INFORMATION
Functions: pipe(2), wait(2), fclose(3), fopen(3), system(3)
Files: stdio(4)
2 Intergraph Corporation - 2/94