简体   繁体   English

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

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

I have a shell script which contains the following lines: 我有一个shell脚本,其中包含以下行:

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

In my C program I use popen to execute the script like this: 在我的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
}

Now, how do I get the exit code of the script? 现在,我如何获得脚本的退出代码? I tried using WEXITSTATUS , but it does not work: 我尝试使用WEXITSTATUS ,但它不起作用:

WEXITSTATUS(pclose(shell))

After you have closed a stream, you cannot perform any additional operations on it. 关闭流后,您无法对其执行任何其他操作。

You should not call read or write or even pclose after you called pclose on a file object! 在文件对象上调用pclose后,不应该调用readwrite甚至pclose

pclose means you are done with the FILE * and it will free all underlying data structures ( proof ). pclose意味着你完成了FILE *并且它将释放所有底层数据结构( 证明 )。

Calling it the second time can yield anything, including 0 . 第二次调用它可以产生任何东西,包括0

Your code should look like this: 您的代码应如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM