c - 系统函数的返回值

标签 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 命令的退出状态。但是值(value)变得不同了。 为什么?

最佳答案

您忘记阅读整个部分。

[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).

关于c - 系统函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33121631/

相关文章:

c - 如何在 C 中调用带有 "int"参数的函数?

c - Memcpy 字符串作为空指针,读取不正确

c - 无法更改核心转储文件的文件名

linux - 我们如何比较两个程序的依赖关系图?

php - 如何以 root 身份运行 PHP exec()?

c - 我不明白什么时候用箭头,什么时候用点

c - 如何使用 MSVC 内在函数来获得这个 GCC 代码的等价物?

linux - grep:无效的正则表达式

unix - 在shell脚本中设置环境变量不会使其对shell可见

bash - 将 STDOUT 和 STDERR 写入日志文件,同时将 STDERR 写入屏幕