如何获取系统调用调用的程序的退出代码? [英] How to get the exit code of program invoked by system call?
本文介绍了如何获取系统调用调用的程序的退出代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如,Program a.out :
For example, Program a.out:
int main()
{
return 0x10;
}
计划 b.out :
int main()
{
if(system("./a.out") == 0x10)
return 0;
else
return -1;
}
根据 cppreference , system()
的返回值是实现相关的。因此,程序b.out的尝试是明显错误的。
According to cppreference, the return value of system()
is implementation-dependent. Thus, the attempt of program b.out is obvious erroneous.
在上面的情况下,我如何得到 0x10
而不是未确定值?
如果系统调用不是正确的工具,这是正确的方法是什么?
In the case above, how can I get 0x10
instead of an undetermined value?
If system call is not the right tool, what's the proper way to do this?
推荐答案
引用 man system
:
The value returned is -1 on error (e.g. fork(2) failed), and the
return status of the command otherwise. This latter return status is
in the format specified in wait(2). Thus, the exit code of the command
will be WEXITSTATUS(status). In case /bin/sh could not be executed,
the exit status will be that of a command that does exit(127).
您需要使用 WEXITSTATUS
退出代码的命令。您的 bc
需要如下所示:
You need to use WEXITSTATUS
to determine the exit code of the command. Your b.c
needs to look something like:
#include <stdio.h>
#include <sys/wait.h>
int main()
{
int ret = system("./a.out");
if (WEXITSTATUS(ret) == 0x10)
return 0;
else
return 1;
}
这篇关于如何获取系统调用调用的程序的退出代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文