在 C 程序中获取 shell 脚本的退出代码

Getting the exit code of a shell script, in a C program

我有一个 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 之后调用 readwrite 甚至 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));
}
...