How to get the program exit code caused by a system call?

For example, a.out program:

int main()
{
    return 0x10;
}

B.out program:

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

According to cppreference , the return value system()is implementation dependent. Thus, an attempt to b.out is obviously erroneous.

In the above example, how can I get 0x10instead of an undefined value? If a system call is not the right tool, what is the right way to do this?

+4
source share
2 answers

Quote 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 WEXITSTATUSthe command to determine the exit code. Your b.cshould look something like this:

#include <stdio.h>
#include <sys/wait.h>
int main()
{
    int ret = system("./a.out");
    if (WEXITSTATUS(ret) == 0x10)
      return 0;
    else
      return 1;
}
+6
source

unix, fork execve .

:

Program b.out:

int main()
{
    return 0x10;
}

pRogram a.out:

int main()
{
 int pbPid = 0;
 int returnValue;
 if ((pbPid = fork()) == 0)
 {
  char* arg[]; //argument to program b
  execv("pathto program b", arg);
 }
 else
 {
  waitpid(pbPid, &returnValue, 0);
 }
 returnValue = WEXITSTATUS(returnValue);
 return 0;
}
+2

All Articles