如何通过system函数的返回值来判断执行成功与否。

先看下man对于system的描述,

DESCRIPTION

       system()  executes  a  command  specified in command by calling /bin/sh -c command, and returns after the command has
       been completed.

原理就是fork一个子进程,在子进程里执行cmd,最后返回子进程执行结果的状态值。

再看下man对于其返回值的说明,

RETURN VALUE
       The value returned is -1 on error (e.g.  fork(2) failed), and the return status of the command otherwise.  This  lat‐
       ter return status is in the format specified in wait(2). 

返回-1意味着fork失败,这个需要最先判断。如果不是-1的话,则返回子进程的执行结果status,这个status我们可以看下wait(2),里面有2处我们需要关注的,

WIFEXITED(status)
              returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by  returning  from
              main().

WEXITSTATUS(status)
              returns  the  exit  status of the child.  This consists of the least significant 8 bits of the status argument
              that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main().
              This macro should only be employed if WIFEXITED returned true.

可以通过WIFEXITED和WEXITSTATUS宏对status取值来方便我们的判断,其中WIFEXITED可以判断子进程是否正常退出,WEXITSTATUS得到子进程的exit code,正常为0。
 

那么我们就可以这么写,

int status = system(cmd);
if (-1 == status)
{
    return false;
}
if (!WIFEXITED(status))
{
    return false;
}
if (WEXITSTATUS(status))
{
    return false;
}

return true;

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值