c++ - 如何获取 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
任何想法,如何获得退出代码?
解决方案
您应该能够通过检查返回值来获得退出代码:
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++0x是C++11,就在它正式标准化之前,std::error_code
即使您告诉它使用 C++0x,您的标准库也很可能会支持它。
推荐阅读
- laravel - Laravel 5:获取具有不同id的关系模型
- database - 如何使用 pygrametl 将 csv 文件中的 unicode 数据导入数据库?
- javascript - 确切的参数是什么?
- java - 未使用局部变量 conn 的值
- android - onCreate() 方法是如何运行的?
- javascript - Javascript 调试输出
- mips32 - 三个 32 位整数的 MIPS32 乘法
- typescript - 在打字稿中使用对象属性作为类型
- java - Intellij 警告忘记写入二维数组
- python - SublimeText 3 上的 Python 错误 SyntaxError: invalid syntax