2

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?

1

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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..

Comments

0

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

C:/myprogram.exe
echo $?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.