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

标签 c linux shell unix exit-code

我有一个 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));
}
...

关于c - 在 C 程序中获取 shell 脚本的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44528672/

相关文章:

c - 如何用指针变量存储变量

linux - 在 10 点运行命令的脚本

shell - Fish shell 中带花括号的 Subversion 命令

linux - bash 脚本调用显示不一致的行为

c - 使用一个名称的全局链接变量

c - 使用 0b 表示打印 (printf) float

在C中复制字符

linux - 即使管理员将屏幕的 chmod 更改为 700 或 777,如何继续运行屏幕命令

linux - 如何在我的 LKM 和 Linux 内核之间同步共享数据结构?

bash - 在命令中使用多个字符串定界符会导致 mysql 客户端/bash 脚本出现解析问题