Search code examples
clinuxshellunixexit-code

Getting the exit code of a shell script, in a C program


I have a shell script which contains the following lines:

if [ $elof -eq 1 ];
then exit 3
else if [  $elof -lt 1 ];then
    exit 4
else
    exit 5
fi
fi

In my C program I use popen to execute the script like this:

char command[30];
char script[30];
scanf("%s", command);
strcpy(script, "./myscript.sh ");
strcat(script, command);
FILE * shell;
shell = popen(script, "r");
if(WEXITSTATUS(pclose(shell))==3) {
   //code
}
else if(WEXITSTATUS(pclose(shell))==4){
  //code
}

Now, how do I get the exit code of the script? I tried using WEXITSTATUS, but it does not work:

WEXITSTATUS(pclose(shell))

Solution

  • After you have closed a stream, you cannot perform any additional operations on it.

    You should not call read or write or even pclose after you called pclose on a file object!

    pclose means you are done with the FILE * and it will free all underlying data structures (proof).

    Calling it the second time can yield anything, including 0.

    Your code should look like this:

    ...
    int r = pclose(shell);
    if(WEXITSTATUS(r)==3)
    {
                printf("AAA\n");
    }
    else if(WEXITSTATUS(r)==4)
    {
                printf("BBB\n");
    } else {
        printf("Unexpected exit status %d\n", WEXITSTATUS(r));
    }
    ...