c++popenstatusexit-codepclose

Does pclose() return pipe's termination status shifted left by eight bits on all platforms?


I found on Centos4 that the man page for popen() states in part:

DESCRIPTION
   The  pclose()  function shall close a stream that was opened by popen(), wait for the command to termi-
   nate, and return the termination status of the process that was running  the  command  language  inter-
   preter.   However, if a call caused the termination status to be unavailable to pclose(), then pclose()
   shall return -1 with errno set to [ECHILD] to report this situation.

However, in my C++ application, when I actually execute the code, I see that the termination status is shifted left by 8 bits. Perhaps this is to distinguish a -1 from the pipe's termination status from pclose()'s own exit status of -1?

Is this portable behavior? Why doesn't the man page mention this? If not portable, which platforms conform to this behavior?


Solution

  • Just to add some code to shooper's answer above, you may want to do something on the lines of this:

    #include <sys/wait.h>
    
    //Get your exit code...
    int status=pclose(pipe);
    
    //...and ask how the process ended to clean up the exit code.
    if(WIFEXITED(status)) {
        //If you need to do something when the pipe exited, this is the time.
        status=WEXITSTATUS(status);
    }
    else if(WIFSIGNALED(status)) {
        //If you need to add something if the pipe process was terminated, do it here.
        status=WTERMSIG(status);
    }
    else if(WIFSTOPPED(status)) {
        //If you need to act upon the process stopping, do it here.
        status=WSTOPSIG(status);
    }
    

    Other than that, add elegance as needed.