简体   繁体   English

在bash脚本中检查C程序的返回值?

[英]Checking the return value of a C program in a bash script?

I have a bash script in which i check the exit code of a last run command by using $? 我有一个bash脚本,我使用$检查上次运行命令的退出代码? variable but now I am executing a C program (from that script) which returns 0 if the program gets executed successfully. 变量,但现在我正在执行一个C程序(从该脚本),如果程序成功执行,它返回0。 Is there any way I can catch this return value of the C program from with in my bash script? 有什么方法可以在我的bash脚本中捕获C程序的返回值吗?

I believe different commands like awk, sed etc are written in C. How do they use $? 我相信不同的命令,如awk,sed等都是用C语言编写的。他们如何使用$? to store their exit codes in it? 将退出代码存储在其中? How can I make my C program to store its exit code in $?? 如何让我的C程序将其退出代码存储在$ ??

I hope my question is clear. 我希望我的问题很清楚。

There's no need to do anything - if your C program returns 0, that's what will be stored in the $? 没有必要做任何事情 - 如果你的C程序返回0,那将是什么将存储在$? variable of the shell that executed it. 执行它的shell的变量。

bash catches the exit code in $? bash捕获$?的退出代码$? automagically. 自动的。 Or you can just use the command in if if you only care about zero/non-zero. 或者, if您只关心零/非零, if可以使用该命令。

The return code of a C program is the value returned by int main() function or the argument of exit() function. C程序的返回码是int main()函数返回的值或者exit()函数的参数。 The system then makes it available to its parent process through the wait() system call. 然后,系统通过wait()系统调用使其可用于其父进程。 When the parent process is bash , this value is then made available through the $? 当父进程是bash ,这个值可以通过$? variable. 变量。

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

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