[英]How to get the exit code of program invoked by system call?
For example, Program a.out :例如,程序a.out :
int main()
{
return 0x10;
}
Program b.out :程序b.out :
int main()
{
if(system("./a.out") == 0x10)
return 0;
else
return -1;
}
According to cppreference , the return value of system()
is implementation-dependent .根据cppreference ,
system()
的返回值取决于实现。 Thus, the attempt of program b.out is obvious erroneous.因此,程序b.out 的尝试显然是错误的。
In the case above, how can I get 0x10
instead of an undetermined value?在上述情况下,如何获得
0x10
而不是未确定的值? If system call is not the right tool, what's the proper way to do this?如果系统调用不是正确的工具,那么正确的方法是什么?
Quoting man system
:引用
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).
You need to use WEXITSTATUS
to determine the exit code of the command.您需要使用
WEXITSTATUS
来确定命令的退出代码。 Your bc
needs to look something like:你的
bc
需要看起来像:
#include <stdio.h>
#include <sys/wait.h>
int main()
{
int ret = system("./a.out");
if (WEXITSTATUS(ret) == 0x10)
return 0;
else
return 1;
}
If you're on a unix system, you should use fork execve and wait.如果您使用的是 unix 系统,则应该使用 fork execve 并等待。
Here a sample code of your case:这是您案例的示例代码:
Program b.out:
int main()
{
return 0x10;
}
pRogram a.out:
int main()
{
int pbPid = 0;
int returnValue;
if ((pbPid = fork()) == 0)
{
char* arg[]; //argument to program b
execv("pathto program b", arg);
}
else
{
waitpid(pbPid, &returnValue, 0);
}
returnValue = WEXITSTATUS(returnValue);
return 0;
}
system call is good, but you have to pay attention of your command to execute.系统调用是好的,但你必须注意你的命令来执行。 I run something like 'myscript.sh p1 p2 p3 |
我运行类似“myscript.sh p1 p2 p3 | tee /mylog' and got always ok back.
tee /mylog' 并且总是可以回来。 The problem is the pipe.
问题是管道。 system always returned the exit code of the last command which always worked and not the result of the myscript.
系统总是返回最后一个总是有效的命令的退出代码,而不是 myscript 的结果。 So, only use pipe in the command to execute if you don't expect exit code of first command.
因此,如果您不期望第一个命令的退出代码,则仅在命令中使用管道来执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.