c - 为什么 "system"的返回与被调用脚本的返回不匹配?

标签 c linux system

我有一个简单的脚本

#!/usr/bin/bash
# exit5.bash
exit 5

我在c程序中用system调用它

#include <stdlib.h>
#include <stdio.h>

int main()
{
    int ret = system("./exit5.bash");
    printf("%d\n", ret);
    return 0;
}

我看到屏幕上打印了 1280,这与 5 << 8 相同

为什么我看不到常规 5?

最佳答案

system 的返回值是终止状态,而不是退出代码

参见 return value section of man system :

In the last two cases, the return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED(), WEXITSTATUS(), and so on).

WEXITSTATUS 宏返回您要查找的内容:

WEXITSTATUS(wstatus)

returns the exit status of the child. This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main(). This macro should be employed only if WIFEXITED returned true.

关于c - 为什么 "system"的返回与被调用脚本的返回不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56298369/

相关文章:

c - C 中的字符数组是动态的吗?

c - 如何强制 openMP 按特定顺序运行迭代

linux - 如何使用 'system()' 终止在 perl 脚本中启动的命令

architecture - 除了Erlang之外,还有哪些其他系统基于 "Green Processes"?

c - LwIP 实现

c - 在c中打开位于不同位置的文件

c# - 从 C# 应用程序远程运行 sudo 命令时出现问题。

linux - 在 NodeJS 进程中创建 bash 包装器

caching - 直接映射缓存如何工作?

python - 停止调用新的 Shell/cmd 提示符,python