Get bash completion code into c program  Topic is solved

Get your foo on.

Get bash completion code into c program

Postby BowCatShot » September 29th, 2018, 4:54 pm

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?

Thanks
BowCatShot
BowCatShot
 
Posts: 68
Joined: May 10th, 2014, 2:29 pm

Re: Get bash completion code into c program

Postby nodir » September 29th, 2018, 5:35 pm

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:
return_of_cmd_x="$?"
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
nodir
 
Posts: 287
Joined: June 16th, 2015, 10:10 pm

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

Postby BowCatShot » September 29th, 2018, 7:12 pm

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.
BowCatShot
 
Posts: 68
Joined: May 10th, 2014, 2:29 pm


Return to Programming

Who is online

Users browsing this forum: No registered users and 1 guest

cron

x