linux的system函数返回值,关于libc中的system()函数的返回值

先看一个简单的程序:

#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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值