【问题标题】:Exit Codes from system() not as expectedsystem() 的退出代码与预期不符
【发布时间】:2012-11-06 16:05:55
【问题描述】:

system() 函数似乎返回了我从它所调用的进程中获得的退出代码的 128 倍。

来自手册页:

返回值 错误时返回的值为 -1(例如,fork(2) 失败),以及命令的返回状态 other- 明智的。

这就是我所拥有的。

$ ls tinker.c
tinker.c
$ echo $?
0
$ ls notexisting
ls: cannot access notexisting: No such file or directory
$ echo $?
2
$ cat tinker.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("%d\n", system("ls tinker.c"));
    printf("%d\n", system("ls notexisting"));
    return 0;
}
$ gcc tinker.c -o tinker
$ ./tinker 
tinker.c
0
ls: cannot access notexisting: No such file or directory
512

第一次调用表明我没有遇到失败,但返回代码看起来与我从手册页中读取的内容完全不同。我做错了什么?

【问题讨论】:

    标签: c linux freebsd


    【解决方案1】:

    来自 POSIX system(3):

    如果 command 不是空指针,system() 将返回命令语言解释器的终止状态以 waitpid() 指定的格式

    要获取返回码,需要使用WEXITSTATUS宏。

    【讨论】:

      【解决方案2】:

      您对系统手册页的引用遗漏了相关部分:

      ... 后一种返回状态采用 wait(2) 中指定的格式。 因此,该命令的退出代码将是 WEXITSTATUS(status)。

      您需要将返回值右移 8 位(至少在 Linux 上),以获取命令退出代码。

      可移植的方法是只使用宏本身。

      【讨论】:

        【解决方案3】:

        0和512是命令的终止状态

        如果命令执行成功,则返回 0 值,否则返回非零值。而且这个非零值在不同的操作系统中是不同的。在我的mac os中,第二个system命令的返回值为256。

        你也可以从这个问题`ls` exit status得到答案。

        【讨论】:

        • "0和512是命令的终止状态。"不一定。请看其他答案的推理。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多