How to get the return code from a batch/shell script that launched from C++ code

7.3k views Asked by At

We have a C++ program, sometimes this program need to execute a user defined batch/shell/ant script. We are not able to control how this script runs. Is there a way to get the return code from C++ program?

Something like: exec a script.sh > status.tmp ?

We need to support both Windows and Linux.

Any ideas?

3

There are 3 answers

0
woggioni On BEST ANSWER

in linux just use

int ret=system("myshellscrtipt.sh");

since the return value of the script is the return value of the system function. In Windows I'dont't know wether there is a similar function. If you used the Qt toolkit you could do something like this

QProcess process;

process.start( "yourShellCommand", QStringList( args );

and this would be really cross-platform..

0
chandank On

Another simple of going this is get the return using the marco WEXITSTATUS. Pretty much the same way that you get return values of child process using waitpid call (in Unix based systems).

Here is the sample program. I have one C/C++ program, and one simple bash script.

Sample bash script

#!/bin/bash
echo "I am in Script"
exit 5;

Sample C/C++ program

int i, ret = system("./b.sh 2>&1 > /dev/null");
i=WEXITSTATUS(ret);
printf("My val= %d\n",i);

Output

./a.out 
My val= 5

If you want more advanced approach to have multiple return code from the script or want an interactive session then perhaps you should use popen

Hope this helps.

0
qstebom On

In bash the status code is stored in a special variable:

C:/myprogram.exe
echo $?