我在 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/