Page 1 of 1

Get bash completion code into c program

PostPosted: September 29th, 2018, 4:54 pm
by BowCatShot
I can run bash commands from within my c program via the "system" statement. The return result
from system is just about whether that call was successful. But whatever bash statement that I run from
the system call will deposit its completion code into the $? variable. How do I get the value of $? back into the c program?


Re: Get bash completion code into c program

PostPosted: September 29th, 2018, 5:35 pm
by nodir
Pretty sure that is not what you ask for ...
In Bash itself you would "get" the exid code of the last command by simply using $?. Most of the time it get's done via || or && or with the test command ( [ or [[ )
for example:
cd /etc/ssh || exit (if the exit code ain't 0 - true, you will run a different command, in this case exit)
You could of course simply echo it
echo $?
or assing it to a variable to mangle with it:
The || or && or [[ way is prefered, as far i can tell, assigning it seems to be superfluous most of the time.

If you can make use of
var="$?" in C with a system statement i don't know. Same for the echo approach.
That is what you asked, so sorry for all the noise you probably know already. If it is urgent you may want to ask in the #bash irc channel (quite some seem to be in C too).
Good luck.

PS: a very awkard and unsexy approach would be to store the value of $? in a temporary file and read that file via the according C code:
cd /etc/ssl; echo $? > /tmp/cd_exit_code

Re: Get bash completion code into c program  Topic is solved

PostPosted: September 29th, 2018, 7:12 pm
by BowCatShot
Thank you, nodir.

After much searching, I ran across this:

Code: Select all
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

int main() {

printf("program returned %d\n", WEXITSTATUS(system("ls dummy")));

If you issue the ls dummy statement in bash, and there is no file dummy, then ls exits with 2. And
that's what the little c example shows.