先看一个简单的程序:
#include
#include
int main(int argc, const char **argv) {
int ret=0;
ret=system("abc");
//printf("%d",ret);
return ret;
}
abc是一个不存在命令
按我一直以来的理解,system()的返回值即为所执行命令的返回值
打印了来的ret值为32512
可是执行完这个c程序后,执行echo $?你会发现始终是0
明明printf出来是32512为什么,echo $?出来是0
百思不得其解,请教了冷波才最终解决
libc的man中有这么一段
Otherwise, the return value is the exit status of the child process in its lower 8 bits; bits 8-17 of the return value will hold SIGINT or SIGABRT if the child process was aborted by Ctrl-C or Critical Device Error, respectively; otherwise they will be zero(4). If the child couldn’t be run, system will return -1 and set errno to an appropriate value. Note that if `COMMAND.COM’ was used to run the child, it will always return a 0 status, even if the command didn’t run successfully. However, system only calls `COMMAND.COM’ when it needs to run commands internal to it.
原来system函数返回,取高八位作为子进程的status
32512=0x7f00
而bash取的是返回值最大为8位,所以对于对于直接取自system的返回,echo $?其低8位永远是0
正确的程序是:
#include
#include
int main(int argc, const char **argv) {
int ret=0;
ret=system("abc");
return ret>>8;
}