先看下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;