我有一个 shell 脚本,其中包含以下几行:
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))
最佳答案
After you have closed a stream, you cannot perform any additional operations on it.
在对文件对象调用 pclose
之后,您不应该调用 read
或 write
甚至 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));
}
...
关于c - 在 C 程序中获取 shell 脚本的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44528672/