system() 的退出代码不符合预期

Ish*_*eck 5 c linux freebsd

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
Run Code Online (Sandbox Code Playgroud)

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

Mat*_*Mat 3

来自 POSIX system(3)

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

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