Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the exit code of program invoked by system call?

Tags:

c++

For example, Program a.out:

int main()
{
    return 0x10;
}

Program b.out:

int main()
{
    if(system("./a.out") == 0x10)
       return 0;
    else
       return -1;
}

According to cppreference, the return value of system() is implementation-dependent. Thus, the attempt of program b.out is obvious erroneous.

In the case above, how can I get 0x10 instead of an undetermined value? If system call is not the right tool, what's the proper way to do this?

like image 742
southp Avatar asked Nov 25 '13 12:11

southp


Video Answer


3 Answers

Quoting man system:

The value returned is -1 on  error  (e.g.   fork(2)  failed),  and  the
return  status  of the command otherwise.  This latter return status is
in the format specified in wait(2).  Thus, the exit code of the command
will  be  WEXITSTATUS(status).   In case /bin/sh could not be executed,
the exit status will be that of a command that does exit(127).

You need to use WEXITSTATUS to determine the exit code of the command. Your b.c needs to look something like:

#include <stdio.h>
#include <sys/wait.h>
int main()
{
    int ret = system("./a.out");
    if (WEXITSTATUS(ret) == 0x10)
      return 0;
    else
      return 1;
}
like image 67
devnull Avatar answered Oct 03 '22 06:10

devnull


If you're on a unix system, you should use fork execve and wait.

Here a sample code of your case:

Program b.out:

int main()
{
    return 0x10;
}

pRogram a.out:

int main()
{
 int pbPid = 0;
 int returnValue;
 if ((pbPid = fork()) == 0) // Fork create a child process
 {
  // Only executed in child process
  char* arg[]; //argument to program b
  execv("pathto program b", arg);
  exit(34);
 }
 else
 {
  // Only executed in parent(original) process
  waitpid(pbPid, &returnValue, 0);
 }
 returnValue = WEXITSTATUS(returnValue);
 // returnValue will be 34 if exeve failed
 return 0;
}
like image 41
izissise Avatar answered Oct 03 '22 04:10

izissise


system call is good, but you have to pay attention of your command to execute. I run something like 'myscript.sh p1 p2 p3 | tee /mylog' and got always ok back. The problem is the pipe. system always returned the exit code of the last command which always worked and not the result of the myscript. So, only use pipe in the command to execute if you don't expect exit code of first command.

like image 22
Thomas Avatar answered Oct 03 '22 05:10

Thomas