tags:

views:

141

answers:

3

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?

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 $??

I hope my question is clear.

+1  A: 

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

Ignacio Vazquez-Abrams
+3  A: 

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.

anon
The exit status is limited to only 8 bits, so only the lowest 8 bits of what the program returns will end up stored in $?
Chris Dodd
@Chris Dodd - POSIX limits the return value to be from 0 - 255 anyway, so 8 bit storage isn't a problem there, its an optimization.
Tim Post
+1  A: 

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.

mouviciel
What makes you think errno is involved?
anon
I make the assumption that a new process is created with `fork()` and its man page mentions that. Am I wrong?
mouviciel
anon
After further research, I found that I am wrong. The exit code of the child process is retrieved by its parent process via the wait() system call. I speak of Unix, I don't know Windows. I edit my answer. Thank you for your intervention.
mouviciel