【问题标题】:Why does the return from "system" not match the return of the script that was called?为什么“系统”的返回与被调用脚本的返回不匹配?
【发布时间】:2019-10-11 09:28:10
【问题描述】:

我有一个简单的脚本

#!/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 &lt;&lt; 8 相同

为什么我看不到常规的 5?

【问题讨论】:

    标签: c linux system


    【解决方案1】:

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

    return value section of man system

    在最后两种情况下,返回值是一个“等待状态”,可以使用waitpid(2) 中描述的宏进行检查。 (即WIFEXITED()WEXITSTATUS() 等)。

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

    WEXITSTATUS(wstatus)

    返回孩子的退出状态。这由状态参数的最低有效 8 位组成,子进程在对 exit(3)_exit(2) 的调用中指定或作为 main() 中的 return 语句的参数。仅当 WIFEXITED 返回 true 时才应使用此宏。

    【讨论】:

    • 特别是在这种情况下你想要printf("%d\n", WEXITSTATUS(ret)); tbc。使用-D_GNU_SOURCE-D_XOPEN_SOURCE=500 或更高版本进行编译。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-19
    • 2012-01-24
    • 2014-01-23
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    • 1970-01-01
    相关资源
    最近更新 更多