system()函数似乎返回了我从它引起的进程中获得的退出代码的128倍.
从手册页:
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
第一个调用表明我没有收到故障,但返回代码看起来与我从手册页中读取的内容完全不同.我做错了什么?
解决方法:
从POSIX system(3)
:
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宏.