2015-11-19 79 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

相关问题