首页 > 解决方案 > 如何获取 Boost 进程的退出代码?

问题描述

我想知道如何获取我的子进程的退出代码。函数 exit_code() 总是返回 0,不管是终止(发送 SIGKILL)还是正确完成。

我正在使用 boost ver 1.65 和 C++0x。我无法更改这些设置。

正如我在文档中读到的:

int exit_code() 常量;

获取 exit_code。如果孩子没有被等待或被终止,则返回值没有任何意义。

所以这个功能对我没有帮助,但我可以使用错误代码。

std::error_code ec;
bp::system("g++ main.cpp", ec);

但 std::error_code 仅从 c++11 开始受支持。我试过 boost::system::error_code,但那不正确。

这里是 Boost::process 的链接: https ://www.boost.org/doc/libs/1_65_0/doc/html/boost_process/tutorial.html

任何想法,如何获得退出代码?

标签: c++boostsignals

解决方案


您应该能够通过检查返回值来获得退出代码:

int ec = bp::system("g++ main.cpp");

采用 an 的重载std::error_code仅用于处理g++首先不存在的边缘情况(因此它永远无法启动可执行文件,因此没有退出代码)。如果您不使用该函数,它将在失败时抛出异常。1

try {
    int ec = bp::system("g++ main.cpp");
    // Do something with ec
} catch (bp::process_error& exception) {
    // g++ doesn't exist at all
}

g++一种更简洁的方法是首先通过搜索环境变量来解决自己的$PATH问题(就像你的 shell 一样):

auto binary_path = bp::search_path(`g++`);
if (binary_path.empty()) {
    // g++ doesn't exist
} else {
    int ec = bp::system(binary_path, "main.cpp");
}

1但是请注意,C++0xC++11,就在它正式标准化之前,std::error_code即使您告诉它使用 C++0x,您的标准库也很可能会支持它。


推荐阅读