在 bash 脚本中检查 C 程序的返回值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2310021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Checking the return value of a C program in a bash script?
提问by Usman
I have a bash script in which i check the exit code of a last run command by using $? variable but now I am executing a C program (from that script) which returns 0 if the program gets executed successfully. Is there any way I can catch this return value of the C program from with in my bash script?
我有一个 bash 脚本,我在其中使用 $? 变量,但现在我正在执行一个 C 程序(来自该脚本),如果程序成功执行,则返回 0。有什么方法可以从我的 bash 脚本中捕获 C 程序的返回值?
I believe different commands like awk, sed etc are written in C. How do they use $? to store their exit codes in it? How can I make my C program to store its exit code in $??
我相信像 awk、sed 等不同的命令是用 C 编写的。他们如何使用 $?将他们的退出代码存储在其中?如何让我的 C 程序将其退出代码存储在 $??
I hope my question is clear.
我希望我的问题很清楚。
回答by
There's no need to do anything - if your C program returns 0, that's what will be stored in the $?variable of the shell that executed it.
无需执行任何操作 - 如果您的 C 程序返回 0,那么它将存储在$?执行它的 shell的变量中。
回答by Ignacio Vazquez-Abrams
bash catches the exit code in $?automagically. Or you can just use the command in ifif you only care about zero/non-zero.
bash$?自动捕获退出代码。或者,if如果您只关心零/非零,则可以仅使用该命令。
回答by mouviciel
The return code of a C program is the value returned by int main()function or the argument of exit()function. The system then makes it available to its parent process through the wait()system call. When the parent process is bash, this value is then made available through the $?variable.
C 程序的返回码是int main()函数返回的值或函数的参数exit()。然后系统通过wait()系统调用将其提供给其父进程。当父进程为 时bash,该值将通过$?变量提供。

