2015-11-19 125 views
0

我有一個C代碼在shell上執行一些命令。該代碼是這樣的:如何獲取shell命令的退出狀態[在C中通過system()運行)?

int main(){ 
      int x=0; 
      x=system("some command"); 
      printf("Exit Status:%d\n",x); 
      return 0; 
} 

這裏的問題是發生故障時,我得到比出口值的其他一些值到X。

假設如果我們在bash上執行xyz,它將以status = 127作爲命令未找到而退出,如果命令存在並且失敗,則爲1。如何將這127或1加入我的C代碼中。

+1

順便提一句,'system()'不使用bash,它使用'/ bin/sh'。因此,在標題中標記這個問題「bash」或使用「bash」是不正確的。 –

回答

3

(至少在Linux上)使用相關waitpid(2)

int x = system("some command"); 
if (x==0) 
    printf("command succeeded\n"); 
else if (WIFSIGNALED(x)) 
    printf("command terminated with signal %d\n", WTERMSIG(x)); 
else if (WIFEXITED(x)) 
    printf("command exited %d\n", WEXITSTATUS(x)); 

等宏。詳細瞭解system(3)。當傳遞給system某些運行時生成的字符串時,請注意code injection

相關問題