LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   How to get return value from C function using shell (https://www.linuxquestions.org/questions/programming-9/how-to-get-return-value-from-c-function-using-shell-627167/)

yhacks 03-11-2008 04:28 AM

How to get return value from C function using shell
 
Hi, I have written script which prints output from the executable to standard output as well as in a file. Here "add" is an c executable which returns
some value based on inputs.

But if tee is not used "$?" returns the return value from add exe.
If tee is used it is simply retuning 0.

echo "Running program output"
myLine="./add 1 11"
`expr "$myLine"`| tee outputfile
echo "Succ/Fail : $?"

Used PIPESTATUS also but seems not working when running the script using sh.

ta0kira 03-11-2008 11:32 AM

Maybe this will work:
Code:

echo "Running program output"
myLine="./add 1 11"
result=
{ eval $myLine; result=$?; } | tee outputfile
echo "Succ/Fail : $result"

ta0kira

matthewg42 03-11-2008 11:48 AM

The convention is to use the error level of the program (i.e. the return value from it's main() function) as a diagnostic to tell if a program ran successfully or not. You should only return positive integers from 0 to 128 from your program, so as a calculator it's not very useful to use this value to return the result of your calculation.

Instead you should print the output of the calculation on stdout (i.e. use printf in your C program), and use the return value from the main function to indicate success or failure. e.g. return non-0 if there was an error, like the user not providing any numbers to add, or some parameter which is not a valid number.

Error messages should be printed to stderr. This was you can capture the correct output with the $(command) syntax (see below), error messages will be displayed on the terminal, and you will have the $? variable to check if there was an error.

Then you could call it like this from a bash script:
Code:

output=$(./add 1 11)
echo "the error level was $? ; the output from the program was: $output"


bigearsbilly 03-11-2008 04:58 PM

Quote:

Originally Posted by yhacks (Post 3084796)
But if tee is not used "$?" returns the return value from add exe.
If tee is used it is simply retuning 0.

$? is set to the exit code of the last command executed in a pipeline.
so the tee masks your program

it is customary to return zero for success, non-zero for an error.
the exit code is only for exit status, the lower order byte
is an error code, the higher order is a bitmask containing signal
status and maybe other stuff like core file production.


All times are GMT -5. The time now is 12:09 PM.