1. 程式人生 > >Linux中system函式返回值詳解

Linux中system函式返回值詳解

描述

system()庫函式使用fork(2)建立一個子程序,該子程序使用execl(3)執行指定的shell命令,

execl(“/bin/sh”, “sh”, “-c”, command, (char *) 0);

標頭檔案

system - execute a shell command
#include <stdlib.h>
int system(const char *command);

返回值 

  • 如果子程序無法建立,或者其狀態不能被檢索,則返回值為-1;
  • 如果在子程序中不能執行一個shell,或shell未正常的結束,返回值被寫入到status的低8~15位元位中;一般為127值
  • 如果所有系統呼叫都成功, 將shell返回值填到status的低8~15位元位中

系統巨集

  • 系統中提供了兩個巨集WIFEXITED(status)、WEXITSTATUS(status)判斷shell的返回值

    • WIFEXITED(status) 用來指出子程序是否為正常退出的,如果是,它會返回一個非零值
    • WEXITSTATUS(status) 用來獲取返回值status的低8~15資料

有了這兩個巨集程式碼就簡介很多, 總結一下,system的返回值需要通過以下三個步驟確定

  • 首先判斷子程序是否成功, status != -1;
  • 判斷子程序是否正常退出, WIFEXITED(status)是否非零;
  • 子程序的返回值, WEXITSTATUS(status) == 0 ;
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

int main()
{
    pid_t status; 
    status = system("./test.sh");
    printf("exit status value = [0x%x]\n", status);
    if (WIFEXITED(status))
    {
        if (0 == WEXITSTATUS(status))
        {
            printf
("run sucess\n"); } else { printf("run fail, exit code: %d\n", WEXITSTATUS(status)); } } else { printf("exit status = [%d]\n", WEXITSTATUS(status)); } }

參考