Search code examples
cpipeposix

How do I detect a failing command in popen?


I'm trying to figure out how to detect when a command invoked by popen fails. In the program test.c below, popen returns non-null although the command fails. Any clues?

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    int status;

    fp = popen("foo", "r");
    if (fp != NULL) {
        puts("command successful");
        status = pclose(fp);
        if (status < 0) {
            perror(NULL);
            exit(EXIT_FAILURE);
        }
    } else {
        perror(NULL);
        exit(EXIT_FAILURE);
    }
    return 0;
}

Output:

$ ./test
command successful
sh: 1: foo: not found

Solution

  • As I understand the man page, pclose should return the exit code. You are testing for <0 here, which would be true if pclose itself fails. Testing for >0 would then test if the called program failed (had exit code >0).

    Man page of pclose:

    The pclose() function waits for the associated process to terminate and returns the exit status of the command as returned by wait4.

    and

    The pclose() function returns -1 if wait4 returns an error, or some other error is detected.