【问题标题】:Unable to correctly interpret return values from system() in c program无法正确解释 c 程序中 system() 的返回值
【发布时间】:2014-07-27 17:34:35
【问题描述】:

操作系统:linux

我无法解释以下程序的输出:

#include <stdlib.h>
#include <sys/mount.h>
#include <errno.h> 
#include <stdio.h>

*****更新代码*****

 void mount_sys() {
    if (0 != mount("none", "/sys", "sysfs", 0, ""))
 {
           /* handle error */
    }
    }


int 
main()
{

int a,b, err;
FILE *file;
err=putenv("PATH=/bin");
printf("putenv return value =%d\n",err);
mount_sys();
;
  err=system("echo 47 > /sys/class/gpio/export");
  if (err == 0) {
    printf("system called good");
  } else {
    perror("Error");
  }

  err=system("echo out > /sys/class/gpio/gpio47/direction");

  if (err == 0) {
    printf("system called good");
  } else {
    perror("Error");
  }

  err=system("echo 1 > /sys/class/gpio/gpio47/value");

  if (err == 0) {
    printf("system called good");
  } else {
    perror("Error");
  }

  return 0;
}

输出

Error: Success
Error: Success
Error: Success

如果所有系统调用都成功的话,我应该会收到 3 次 system called good 消息。

但看起来它失败了。但是为什么使用 perror() 打印的错误是Success ?

【问题讨论】:

  • 为什么不打印出err 的值,看看你实际上从system() 得到的返回值是什么?
  • 你没有声明err变量?
  • 解决这个问题的另一种方法是在 shell 中输入echo 47 &gt; /sys/class/gpio/export(等等),看看会发生什么。您应该得到与使用该命令调用 system 相同的结果。
  • 不管实现问题如何,为此任务使用子流程是相当愚蠢的。只需从您的程序写入 sysfs 节点 - 它会更高效且配置依赖项更少。
  • 感谢您的评论,请告诉我如何使用 sysfs。

标签: c linux


【解决方案1】:

system() 返回的值可以是以下两种情况之一:

shell 命令的退出状态,或者

-1(表示fork()系统调用本身失败)

perror() 仅在第二种情况下相关。正如其他人建议的那样,打印出err 的值,而不是仅仅依靠 perror()。

---- 更新 --- 返回值包括进程的退出状态(前 8 位)和杀死进程的信号 #(如果有,低 8 位)。 32512 == 127

据此: 127 Return code from $?

该返回码表明您尝试运行的命令 (echo) 不在您的 shell 的 PATH 中

【讨论】:

  • 我做了 printf("value return=%d\n",err);但是我得到的值太高了32512,这个值是什么意思?
  • 打印出来的结果是什么?
  • 返回值,我得到的是 32512
  • 我认为我的系统调用工作正常(因为返回值不是-1)。 32512 也是我的 shell 命令的退出状态代码,即 echo。我说的对吗?
  • 为了保持便携性,在system()(如果>0)返回的值上使用WEXITSTATUS()来获取程序退出代码。
【解决方案2】:

处理对system() 的调用的正确方法是:

#include <stdlib.h>
#include <stdio.h>
#include <sys/wait.h> /* For WEXITSTATUS */

int main(void)
{
  int result = EXIT_SUCCESS; /* Be optimistic. */
  char cmd[] = "mycommand";

  int status = system(cmd);
  if (-1 == status)
  {
    perror("system() failed internally");
    result = EXIT_FAILURE;
  }
  else
  {
    fprintf(stderr, "'%s' returned %d.\n", cmd, WEXITSTATUS(status));
  }

  return result;
}

【讨论】:

    猜你喜欢
    • 2018-02-14
    • 2012-01-29
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2018-11-07
    • 2013-03-25
    • 1970-01-01
    • 2012-06-11
    相关资源
    最近更新 更多