如何通过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;

 

 

你可能感兴趣的:(c/c++)