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?