系统功能的返回值

时间:2015-10-14 09:32:13

标签: c linux unix system

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

返回值

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
$ 

以上输出显示,系统函数的返回值为512,ls a命令的退出状态为2. 参考,我希望系统函数的返回值等于ls命令的退出状态。但价值变得不同。 为什么呢?

2 个答案:

答案 0 :(得分:4)

你忘了阅读整个部分。

  

[T]他的返回值是一个“等待状态”即可          使用waitpid(2)中描述的宏进行检查。 (即WIFEXITED()          WEXITSTATUS()等等。

答案 1 :(得分:0)

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