c - 无法正确解释 c 程序中 system() 的返回值

标签 c linux

操作系统: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 ?

最佳答案

处理调用 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;
}

关于c - 无法正确解释 c 程序中 system() 的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24081974/

相关文章:

c++ - 使用 Visual Studio 2017 在 Linux 上构建现有的 C++ 解决方案

c - 如何在 C 程序中使用更大的整数?

php - Ajax 循环每秒从 $.post 获取数据

c - C(或一般过程编程)的设计原则、最佳实践和设计模式?

c++ - 为什么使用 'function address == NULL' 而不是 'false' ?

c++ - YouCompleteMe 无法自动完成

php - 如何更频繁地每分钟运行一次 Cronjobs?

python - 将 Blogger XML 文件转换为 Wordpress WXR - 创建 Python 转换脚本

c - 将 char** 传递给函数,不会改变它的值,还是会改变?

c - c 中的 If 和 Else 语句不起作用