gpt4 book ai didi

c++ - 如何获取系统调用调用的程序的退出码?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:15:19 24 4
gpt4 key购买 nike

例如,程序a.out:

int main()
{
return 0x10;
}

程序b.out:

int main()
{
if(system("./a.out") == 0x10)
return 0;
else
return -1;
}

根据 cppreferencesystem() 的返回值依赖于实现。因此,程序b.out的尝试显然是错误的。

在上面的例子中,我怎样才能得到 0x10 而不是未确定的值?如果系统调用不是正确的工具,那么正确的方法是什么?

最佳答案

引用 man 系统:

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 来确定命令的退出代码。您的 b.c 需要看起来像:

#include <stdio.h>
#include <sys/wait.h>
int main()
{
int ret = system("./a.out");
if (WEXITSTATUS(ret) == 0x10)
return 0;
else
return 1;
}

关于c++ - 如何获取系统调用调用的程序的退出码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20193464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com