popen

execute a command, creating a pipe to it

Synopsis:

#include <stdio.h>
FILE *popen( const char *command,
             const char *mode );

Description:

The popen() function executes the command specified by command and creates a pipe between the calling process and the executed command.

Depending on the mode argument, the stream pointer returned may be used to read from or write to the pipe.

The executed command has the same environment as its parents. The command is started as follows:

spawnl(shell_path, "sh", "-c", command, (char *)NULL );

where shell_path is an unspecified path for the sh utility.

The mode argument to popen() is a string that specifies an I/O mode for the pipe.

  1. If mode is "r", the following occurs when the child process is started:
    • its file descriptor STDOUT_FILENO is the writable end of the pipe
    • the fileno( stream ) in the calling process is the readable end of the pipe, where stream is the stream pointer returned by popen().
  2. If mode is "w", the following occurs when the child process is started:
    • its file descriptor STDIN_FILENO is the readable end of the pipe
    • the fileno( stream ) in the calling process is the writeable end of the pipe, where stream is the stream pointer return by popen()
  3. If mode is any other value, the result is undefined.

A stream opened by popen() should be closed by the pclose() function.

Returns:

The popen() function returns a non-NULL stream pointer on successful completion. If popen() is unable to create either the pipe or the subprocess, a NULL stream pointer is returned, and errno is set appropriately.

Errors:

EINVAL
The mode argument is invalid.

popen() may also set errno values as described by the pipe() and spawnl() functions.

See also:

errno, pclose(), pipe(), spawn... functions

Examples:

/*
 * upper:  executes a given program, converting all input
 *      to upper case.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <unistd.h>
#include <limits.h>

char   buffer[_POSIX_ARG_MAX];

void main( int argc, char **argv )
  {
    int  i;
    int  c;
    FILE *f;

    for( i = 1; i < argc; i++ ) {
      strcat( buffer, argv[i] );
      strcat( buffer, " " );
    }
    if( ( f = popen( buffer, "w" ) ) == NULL ) {
      perror( "popen" );
      exit( 1 );
    }
    while( ( c = getchar() ) != EOF ) {
      if( islower( c ) )
        c = toupper( c );
      putc( c, f );
    }
    pclose( f );
  }

Classification:

UNIX

Systems:

QNX