Reputation: 2893
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?
Upvotes: 2
Views: 7595
Reputation: 739
In bash the status code is stored in a special variable:
C:/myprogram.exe
echo $?
Upvotes: 0
Reputation: 1011
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.
Upvotes: 9
Reputation: 1432
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..
Upvotes: 0