mirror of
https://github.com/arun11299/cpp-subprocess.git
synced 2025-08-04 12:26:19 -04:00

It's useful to be able to know the exit code of the process when it fails with a non-zero exit code. To get this to work, I had to fix a bug in the implementation of check_output. Previously, check_output would call both `p.communicate()` and `p.poll()`. The former has the effect of waiting for EOF on the input and then waiting for the child to exit, reaping it with `waitpid(2)`. Unfortunately, `p.poll()` was hoping to be able to also use `waitpid(2)` to retrieve the exit code of the process. But since the child had already been reaped, the given pid no longer existed, and thus `waitpid(2)` would return `ECHILD`. Luckily the call to `p.poll()` is unnecessary, as the process already provides `p.retcode()` for retrieving the exit code.
52 lines
1.2 KiB
C++
52 lines
1.2 KiB
C++
#include <iostream>
|
|
#include "../subprocess.hpp"
|
|
|
|
namespace sp = subprocess;
|
|
|
|
void test_ret_code()
|
|
{
|
|
std::cout << "Test::test_poll_ret_code" << std::endl;
|
|
auto p = sp::Popen({"/usr/bin/false"});
|
|
while (p.poll() == -1) {
|
|
#ifndef _MSC_VER
|
|
usleep(1000 * 100);
|
|
#endif
|
|
}
|
|
assert (p.retcode() == 1);
|
|
}
|
|
|
|
void test_ret_code_comm()
|
|
{
|
|
using namespace sp;
|
|
auto cat = Popen({"cat", "../subprocess.hpp"}, output{PIPE});
|
|
auto grep = Popen({"grep", "template"}, input{cat.output()}, output{PIPE});
|
|
auto cut = Popen({"cut", "-d,", "-f", "1"}, input{grep.output()}, output{PIPE});
|
|
auto res = cut.communicate().first;
|
|
std::cout << res.buf.data() << std::endl;
|
|
|
|
std::cout << "retcode: " << cut.retcode() << std::endl;
|
|
}
|
|
|
|
void test_ret_code_check_output()
|
|
{
|
|
using namespace sp;
|
|
bool caught = false;
|
|
try {
|
|
auto obuf = check_output({"/bin/false"}, shell{false});
|
|
assert(false); // Expected to throw
|
|
} catch (CalledProcessError &e) {
|
|
std::cout << "retcode: " << e.retcode << std::endl;
|
|
assert (e.retcode == 1);
|
|
caught = true;
|
|
}
|
|
assert(caught);
|
|
}
|
|
|
|
int main() {
|
|
// test_ret_code();
|
|
test_ret_code_comm();
|
|
test_ret_code_check_output();
|
|
|
|
return 0;
|
|
}
|