The Marvelous popen() Function

To launch and run another program from within your code, use the system() function. When your code must examine or save that program’s output, use the popen() function.

Like system(), popen() starts a second program or process, which is where the p comes from.

The open part from popen() is the same open found in the fopen() function. Similar to that function, popen() (say “pee-open”) opens a process for input or output. The popen() function uses a program name as its first argument. The second argument is a file mode, such as "r" to read, "w" to write, or "r+" for both.

Once opened, the same FILE type pointer is used as a reference.

When open for input (as shown below), the spawned program’s output is captured. Use the standard file-reading functions to process the second program’s output.

When the spawned process ends, or your code has read enough, use the pclose() function to terminate the stream.

Both popen() and pclose() require inclusion of the stdio.h header file.

In the following code, the popen() function launches the ver or uname command. ver is the DOS command to display the operating system version; uname is the corresponding Unix command. Ensure that you make the proper change in the code to set the right popen() statement.

#include <stdio.h>

int main()
{
    FILE *p;
    int ch;

    p = popen("ver","r");   /* DOS */
/*  p = popen("uname","r"); /* Unix */
    if( p == NULL)
    {
        puts("Unable to open process");
        return(1);
    }
    while( (ch=fgetc(p)) != EOF)
        putchar(ch);
    pclose(p);

    return(0);
}

Here’s a sample run:

Microsoft Windows [Version 6.1.7601]

I’ve used popen() in my code to read and store output from another program. Specifically, popen() spawned a utility and my code used that utility’s output to help process some data. Storing input from another program works just like storing input from a file. So it may sound crazy, but it’s not.

The popen() function can also write to a program, as well as both read and write, but that’s where things get tricky.

C language stream I/O is buffered. If you plan on writing an interactive program, then you need to know how to manage buffered I/O so that your code doesn’t sit and wait. Such a programming challenge could be highly frustrating. For processing input only, however, popen() is a great function for fetching data generated by another program.

Leave a Reply