system()的退出代码与预期不符 [英] Exit Codes from system() not as expected

查看:70
本文介绍了system()的退出代码与预期不符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

system()函数似乎正在返回128倍于我从其启动的进程中获得的退出代码.

The system() function seems to be returning 128 times the exit code I get from the process it's evoking.

在手册页中:

返回值 发生错误时返回的值为-1(例如fork(2) 失败),并且命令other的返回状态- 明智的.

RETURN VALUE The value returned is -1 on error (e.g., fork(2) failed), and the return status of the command other‐ wise.

这就是我所拥有的.

$ ls tinker.c
tinker.c
$ echo $?
0
$ ls notexisting
ls: cannot access notexisting: No such file or directory
$ echo $?
2
$ cat tinker.c
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    printf("%d\n", system("ls tinker.c"));
    printf("%d\n", system("ls notexisting"));
    return 0;
}
$ gcc tinker.c -o tinker
$ ./tinker 
tinker.c
0
ls: cannot access notexisting: No such file or directory
512

第一次调用表明我没有失败,但是返回代码看起来与我从手册页中读取的内容完全不同.我在做什么错了?

The first call indicates that I'm not getting failures but the return codes look nothing like what I'm reading from the man page. What'm I doing wrong?

推荐答案

从POSIX system(3) :

From POSIX system(3):

如果命令不是空指针,则system()应该以waitpid()指定的格式返回命令语言解释器的终止状态.

If command is not a null pointer, system() shall return the termination status of the command language interpreter in the format specified by waitpid().

要获取返回码,您需要使用WEXITSTATUS宏.

To get the return code, you need to use the WEXITSTATUS macro.

这篇关于system()的退出代码与预期不符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆