如何获取系统调用调用的程序退出代码?

时间:2013-11-25 12:44:19

标签: c++

例如,程序 a.out

int main()
{
    return 0x10;
}

计划 b.out

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

根据cppreferencesystem()的返回值是依赖于实现的。因此,程序b.out的尝试显然是错误的。

在上面的情况中,我如何获得0x10而不是未确定的值? 如果系统调用不是正确的工具,那么正确的方法是什么?

3 个答案:

答案 0 :(得分:6)

引用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).

您需要使用WEXITSTATUS来确定命令的退出代码。您的b.c需要看起来像:

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

答案 1 :(得分:2)

如果您使用的是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 :(得分:1)

系统调用很好,但是您必须注意执行命令。 我运行类似“ myscript.sh p1 p2 p3 | tee / mylog',然后一切正常。 问题是管道。系统总是返回总是有效的最后一个命令的退出代码,而不是myscript的结果。 因此,如果您不希望第一个命令的退出代码,则仅在命令中使用管道执行。

相关问题