【问题标题】:Return value of System Function [duplicate]系统函数的返回值 [重复]
【发布时间】:2016-01-12 07:45:26
【问题描述】:

我试验了系统函数调用。它用于执行程序中的命令。手册页包含以下有关 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 命令的退出状态。但价值变得不同。 为什么?

【问题讨论】:

  • 您可能希望在该值上使用WEXITSTATUS(取决于适当的条件)。
  • 那么,我怎样才能得到传递给系统函数的命令的真正退出状态。
  • 从“If status is not NULL”开始读取链接的文档,大约一半。

标签: c linux unix system


【解决方案1】:

返回值是shell的退出状态,见sh(1)bash(1)或者你在SHELL环境变量中配置的任何东西。顺便说一句,shell 通常会返回最后执行的命令的退出值,但如果您点击了Ctrl-C 键或向进程发送了信号,则情况并非如此。在手册页中查看这些情况下 shell 的退出值。

【讨论】:

    【解决方案2】:

    您忘记阅读整个部分。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2020-02-20
      • 2018-07-04
      • 2019-02-18
      • 2023-04-09
      相关资源
      最近更新 更多