Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...