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

时间:2022-11-01 00:03:24

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.

我希望我的问题很清楚。

3 个解决方案

#1


12  

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的变量。

#2


1  

bash catches the exit code in $? automagically. Or you can just use the command in if if you only care about zero/non-zero.

bash捕获$中的退出代码?自动的。或者,如果您只关心零/非零,则可以使用该命令。

#3


1  

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时,这个值可以通过$?变量。

#1


12  

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的变量。

#2


1  

bash catches the exit code in $? automagically. Or you can just use the command in if if you only care about zero/non-zero.

bash捕获$中的退出代码?自动的。或者,如果您只关心零/非零,则可以使用该命令。

#3


1  

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时,这个值可以通过$?变量。