【问题标题】:Getting the exit code of a shell script, in a C program在 C 程序中获取 shell 脚本的退出代码
【发布时间】:2017-06-13 18:11:32
【问题描述】:

我有一个包含以下几行的 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))

【问题讨论】:

  • 您所展示的内容没有提供足够的上下文。请显示一段完整的代码以及预期和实际输出。
  • 显示更多你的 C 代码...顺便说一句,如果 WIFEXITED() 评估为 true,你应该只使用 WEXITSTATUS()
  • 我已经编辑了我的 C 代码。
  • 不要多次致电pclose(shell)
  • @melpomene 你说得对,我忘了。但是如果我使用WEXITSTATUS 并将其打印到控制台,我会得到 0。但我的脚本仅以 3、4 或 5 退出。这怎么可能?

标签: c linux shell unix exit-code


【解决方案1】:

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));
}
...

【讨论】:

    猜你喜欢
    • 2013-08-28
    • 2013-01-26
    • 1970-01-01
    • 2010-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    相关资源
    最近更新 更多