2017-06-13 98 views
1

我有一个shell脚本,它包含以下几行:得到一个shell脚本的退出代码,在C程序

if [ $elof -eq 1 ]; 
then exit 3 
else if [ $elof -lt 1 ];then 
    exit 4 
else 
    exit 5 
fi 
fi 

在我的C程序中,我使用popen来执行这样的脚本:

char command[30]; 
char script[30]; 
scanf("%s", command); 
strcpy(script, "./myscript.sh "); 
strcat(script, command); 
FILE * shell; 
shell = popen(script, "r"); 
if(WEXITSTATUS(pclose(shell))==3) { 
    //code 
} 
else if(WEXITSTATUS(pclose(shell))==4){ 
    //code 
} 

现在,我该如何获得脚本的退出代码?我试着用WEXITSTATUS,但它不工作:

WEXITSTATUS(pclose(shell)) 
+0

什么你出不给予足够的上下文。请用预期的和实际的输出显示完整的代码。 – dbush

+1

显示更多的C代码... btw,如果WIFEXITED()评估* true,那么应该只使用'WEXITSTATUS()* –

+0

我编辑了我的C代码。 –

回答

3

After you have closed a stream, you cannot perform any additional operations on it.

你不应该叫readwrite甚至pclose你叫一个文件对象上pclose后!

pclose表示您已完成FILE *,它将释放所有基础数​​据结构(proof)。

调用它第二次可以产生任何东西,包括0

您的代码应该是这样的:

... 
int r = pclose(shell); 
if(WEXITSTATUS(r)==3) 
{ 
      printf("AAA\n"); 
} 
else if(WEXITSTATUS(r)==4) 
{ 
      printf("BBB\n"); 
} else { 
    printf("Unexpected exit status %d\n", WEXITSTATUS(r)); 
} 
... 
相关问题