Return 系统函数值

Return value of System Function

我试验了系统函数调用。它用于执行程序中的命令。手册页包含以下有关系统 return 值的信息。

RETURN 值

The value returned is -1 on error (e.g.  fork(2) failed), and the return status of the command otherwise.

根据手册页参考,我检查了以下程序。

节目:

#include<stdio.h>
#include<unistd.h>
int main()
{   
    printf("System returns: %d\n",system("ls a"));
}

输出:

$ ./a.out 
ls: cannot access a: No such file or directory
System returns: 512
$ ls a
ls: cannot access a: No such file or directory
mohanraj@ltsp63:~/Advanced_Unix/Chapter8/check$ echo $?
2
$ 

以上输出表明,return系统函数的值为512,ls a命令的退出状态为2。根据 参考,我希望系统函数的 return 值等于 ls 命令的退出状态。但是价值变得不同了。 为什么?

您忘记阅读整个部分。

[T]he return value is a "wait status" that can be examined using the macros described in waitpid(2). (i.e., WIFEXITED() WEXITSTATUS() and so on).

return 值是 shell 的退出状态,请参阅 sh(1)bash(1) 或您在 SHELL 环境变量中配置的任何内容。顺便说一句,shell 通常是 return 执行的最后一个命令的退出值,但如果您按下 Ctrl-C 键或向进程发送信号,情况就不会如此。在手册页中查看这些情况下 shell 的退出值。