0

I want to get the exit status of a pipe in C++, both on Linux and on Windows, to check whether a command ran successfully.

On Linux (or POSIX more generally), it appears that the macros in <sys/wait.h> are needed to get the correct exit status, such as in the first answer to the question

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

#include <cstdio>
#include <iostream>

#ifdef _WIN32
    #define popen _popen
    #define pclose _pclose
#else
    #include <sys/wait.h>
#endif

int main(){
    FILE* pipe {nullptr};
    pipe = popen( "echo 123", "r" );

    int status {0};
    status = pclose(pipe);

    #ifndef _WIN32
    /* ask how the process ended to clean up the exit code. */
    if ( WIFEXITED(status) ){
        /* Add code here if needed after pipe exited normally */
        status = WEXITSTATUS(status);
    } else if ( WIFSIGNALED(status) ){
        /* Add code here if needed after pipe process was terminated */
        status = WTERMSIG(status);
    } else if ( WIFSTOPPED(status) ){
        /* Add code here if needed after pipe stopped  */
        status = WSTOPSIG(status);
    }
    #else
    /* but what about windows? */
    #endif

    std::cout << "Exit status: " << status << '\n';
    return 0;
}

I couldn't find anything about Windows though. The C runtime lib reference for _pclose includes a remark about _cwait and states that

"The format of the return value [of _pclose] is the same as for _cwait, except the low-order and high-order bytes are swapped".

So how do I get the correct exit status on Windows?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
RL-S
  • 734
  • 6
  • 21
  • Don't spam C tag if your code is C++ – 273K Nov 22 '22 at 15:07
  • 1
    The code is using the C runtime library, and the topic is *exactly* as relevant to C. People who watch the C tag have the same or possibly a higher chance of being able to answer the question. Therefore, I find the tag appropriate. – RL-S Nov 22 '22 at 16:31
  • How about a helpful comment or reply instead? – RL-S Nov 22 '22 at 16:34

0 Answers0