Search code examples
cfopenpopenfgets

popen() is successfull for all commands


No matter what "cmd" string is passed in popen(), it is never FAILING for me

So fp is never NULL even for random "cmd" string.

FILE *fp;
char path[1035];
char cmd = "randomrandomrandom";
fp = popen(cmd, "r");

if (fp == NULL) {
    //Handle Error
    exit(1);
}
while (fgets(path, sizeof(path)-1, fp) != NULL) {
    printf("%s", path);
}
pclose(fp);

Solution

  • popen runs an instance of the shell. Starting a shell normally succeeds. You need to determine if it has terminated successfully. popen itself cannot do that, but pclose can: it returns the status of the child process (or -1 if another error has occurred).

    So in order to verify that the command has been executed successfully, one needs to check return values of both popen and pclose.