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