Linux C++中system()函数调用的返回值,用于运行Python程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10931134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Return value of system() function call in C++, used to run a Python program
提问by Shailesh Tainwala
I am working on Linux with code that makes a system()
call to run a python program. I am interested in the value returned by this function call to understand how the python program execution went.
我正在使用system()
调用运行 python 程序的代码在 Linux 上工作。我对这个函数调用返回的值感兴趣,以了解 python 程序的执行情况。
So far, I have found 3 results:
到目前为止,我发现了 3 个结果:
When the python process completes successfully, value returned by system() is 0
When the python process is killed mid-execution (using
kill -9 pid
), value returned by system() is 9When the python process fails on its own due to incorrect parameters, value returned by system() is 512
当python进程成功完成时,system()返回的值为0
当python进程在执行中(使用
kill -9 pid
)被杀死时,system()返回的值为9当python进程因参数不正确而自行失败时,system()返回的值为512
This does not fit with what I've read about system()function.
这与我读到的有关system()函数的内容不符。
Furthermore, the code for the python program being invoked shows that it exits with sys.exit(2)
when any error is encountered, and sys.exit(0)
when execution completes successfully.
此外,被调用的 python 程序的代码显示,它sys.exit(2)
在遇到任何错误时以及sys.exit(0)
执行成功完成时退出。
Could anyone relate these two? Am I interpreting the return value in a wrong manner? Is there some Linux processing involved that takes the argument of the sys.exit()
function of the python program and returns value of system()
based on it?
谁能把这两个联系起来?我是否以错误的方式解释了返回值?是否涉及一些Linux处理,它接受sys.exit()
python程序函数的参数并system()
基于它返回值?
采纳答案by Some programmer dude
The exit code of the program you call can be fetched with WEXITSTATUS(status)
as per the manual page. Also see the manual page for wait
.
该计划的退出代码调用可以与获取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";
}