c++ - C++中system()函数调用的返回值,用于运行Python程序

标签 c++ python linux system

我在 Linux 上使用代码调用 system() 来运行 python 程序。我对这个函数调用返回的值感兴趣,以了解 python 程序的执行情况。

到目前为止,我找到了 3 个结果:

  • 当 python 进程成功完成时,system() 返回的值为 0

  • 当 python 进程在执行中被杀死时(使用 kill -9 pid),system() 返回的值为 9

  • 当python进程因参数不正确而自行失败时,system()返回值为512

这与我读到的关于 system() 的内容不符功能。

此外,被调用的 python 程序的代码显示它在遇到任何错误时以 sys.exit(2) 退出,并以 sys.exit(0) 当执行成功完成时。

谁能把这两者联系起来?我是否以错误的方式解释了返回值?是否有一些 Linux 处理涉及接受 python 程序的 sys.exit() 函数的参数并返回基于它的 system() 的值?

最佳答案

根据 manual page,可以使用 WEXITSTATUS(status) 获取您调用的程序的退出代码.另请参阅 wait 的手册页.

int status = system("/path/to/my/program");
if (status < 0)
    std::cout << "Error: " << strerror(errno) << '\n';
else
{
    if (WIFEXITED(status))
        std::cout << "Program returned normally, exit code " << WEXITSTATUS(status) << '\n';
    else
        std::cout << "Program exited abnormaly\n";
}

关于c++ - C++中system()函数调用的返回值,用于运行Python程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931134/

相关文章:

c++ - 这是否被认为是内存泄漏?

c++ - 对 vector 的引用在回退后是否会重新定位?如果是,如何?

c - 为什么 struct stat 中的 st_size 字段是有符号的?

python - 避免使用 Python 中的全局变量,我有几个函数可以更改一个变量

python - 如果解释了Python,那么什么是.pyc文件?

Linux SIGPIPE 服务器崩溃

linux - 使用 bash 进行文本操作

c++ - 什么是 C++ 中的早期(静态)和晚期(动态)绑定(bind)?

c++ - 这个 C++ 解析器是如何工作的?

python - 使用模块编译的 Python 代码的版本兼容性