linux c system返回值問題總結

先看例子shell

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 
#include <sys/types.h> 

int main() 
{ 
pid_t status; 


status = system("./test.sh"); 

if (-1 == status) 
{ 
printf("system error!"); 
} 
else 
{ 
printf("exit status value = [0x%x]\n", status); 
//status 低7bits表示致使任務退出的信號數值,右起第8bit表示是否生成coredump文件;

//高8位是實際的exit參數值。宏的時間參見標註c頭文件

if (WIFEXITED(status)) //正確退出
{ 
if (0 == WEXITSTATUS(status)) //操做成功
{ 
printf("run shell script successfully.\n"); 
} 
else //操做失敗
{ 
printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status)); 
} 
} 
else //錯誤退出,這裏屬於信號中斷了,WEXITSTATUS必定是0了
{ 
printf("exit status = [%d]\n", WEXITSTATUS(status)); 
} 
} 

return 0; 
} 
View Code

 

下面更詳細解釋:安全

一、先統一兩個說法:ide

(1)system 返回值:指調用system函數後的返回值,好比上例中status爲system返回值函數

(2)shell 返回值:指system所調用的shell命令的返回值,好比上例中,test.sh中返回的值爲shell返回值。spa

 

二、如何正確判斷test.sh是否正確執行?code

都錯!(僅僅判斷status是否==0?或者僅判斷status是否!=-1? )orm

 

三、man中對於system的說明blog

RETURN VALUE進程

The value returned is -1 on error (e.g. fork() failed), and the returnip

status of the command otherwise. This latter return status is in the

format specified in wait(2). Thus, the exit code of the command will

be WEXITSTATUS(status). In case /bin/sh could not be executed, the

exit status will be that of a command that does exit(127).

看得很暈吧?

 

四、system函數對返回值的處理。

階段1:

建立子進程等準備工做。若是失敗,返回-1。

階段2:

調用/bin/sh拉起shell腳本,若是拉起失敗或者shell未正常執行結束(參見備註1),緣由值被寫入到status的低8~15比特位中。

如何判斷階段2中,shell腳本是否正常執行結束呢?系統提供了宏:WIFEXITED(status)。若是WIFEXITED(status)爲真,則說明正常結束。

階段3:

若是shell腳本正常執行結束,將shell返回值填到status的低8~15比特位中。

如何取得階段3中的shell返回值?你能夠直接經過右移8bit來實現,但安全的作法是使用系統提供的宏:WEXITSTATUS(status)。

備註1:

只要可以調用到/bin/sh,而且執行shell過程當中沒有被其餘信號異常中斷,都算正常結束。

好比:

無論shell腳本中返回什麼緣由值,是0仍是非0,都算正常執行結束。即便shell腳本不存在或沒有執行權限,也都算正常執行結束。

若是shell腳本執行過程當中被強制kill掉等狀況則算異常結束。

相關文章
相關標籤/搜索