例:
status = system("./test.sh");
1、先統一兩個說法:(1)system傳回值:指調用system函數後的傳回值,比如上例中status為system傳回值(2)shell傳回值:指system所調用的shell命令的傳回值,比如上例中,test.sh中返回的值為shell傳回值。
2、如何正確判斷test.sh是否正確執行?僅判斷status是否==0?或者僅判斷status是否!=-1?
都錯!
3、man中對於system的說明
RETURN VALUE
The value returned is -1 on error (e.g. fork() failed), and the return
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函數對傳回值的處理,涉及3個階段:階段1:建立子進程等準備工作。如果失敗,返回-1。階段2:調用/bin/sh拉起shell指令碼,如果拉起失敗或者shell未正常執行結束(參見備忘1),原因值被寫入到status的低8~15位元位中。system的man中只說明了會寫了127這個值,但實測發現還會寫126等值。階段3:如果shell指令碼正常執行結束,將shell傳回值填到status的低8~15位元位中。備忘1:只要能夠調用到/bin/sh,並且執行shell過程中沒有被其他訊號異常中斷,都算正常結束。比如:不管shell指令碼中返回什麼原因值,是0還是非0,都算正常執行結束。即使shell指令碼不存在或沒有執行許可權,也都算正常執行結束。如果shell指令碼執行過程中被強制kill掉等情況則算異常結束。
如何判斷階段2中,shell指令碼是否正常執行結束呢?系統提供了宏:WIFEXITED(status)。如果WIFEXITED(status)為真,則說明正常結束。如何取得階段3中的shell傳回值?你可以直接通過右移8bit來實現,但安全的做法是使用系統提供的宏:WEXITSTATUS(status)。
由於我們一般在shell指令碼中會通過傳回值判斷本指令碼是否正常執行,如果成功返回0,失敗返回正數。所以綜上,判斷一個system函數調用shell指令碼是否正常結束的方法應該是如下3個條件同時成立:(1)-1 != status(2)WIFEXITED(status)為真(3)0 == WEXITSTATUS(status)
注意:根據以上分析,當shell指令碼不存在、沒有執行許可權等情境下時,以上前2個條件仍會成立,此時WEXITSTATUS(status)為127,126等數值。所以,我們在shell指令碼中不能將127,126等數值定義為傳回值,否則無法區分中是shell的傳回值,還是調用shell指令碼異常的原因值。shell指令碼中的傳回值最好多1開始遞增。
判斷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); 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 { printf("exit status = [%d]\n", WEXITSTATUS(status)); } } return 0; }
WIFEXITED(stat_val) Evaluates to a non-zero value if status
was returned for a child process that
terminated normally.
WEXITSTATUS(stat_val) If the value of WIFEXITED(stat_val) is
non-zero, this macro evaluates to the
low-order 8 bits of the status argument
that the child process passed to _exit()
or exit(), or the value the child
process returned from main().