探究Linux系統中的system函數返回值

system:

感性認識:

systerm兩層含義:

1、正確退出後。還需要再判斷,操作成功或者操作失敗。

2、錯誤退出。

#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;  
} 

下面更詳細解釋:

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).

看得很暈吧?

4、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掉等情況則算異常結束。


英文說明:

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().




發佈了37 篇原創文章 · 獲贊 30 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章