【问题标题】:Single-threaded way to get a return code from child process using "return" in child使用子进程中的“return”从子进程获取返回码的单线程方法
【发布时间】:2018-03-06 03:59:00
【问题描述】:

如果这看起来重复但我找不到我正在寻找的答案,我深表歉意。我要做的是在我的 C 程序中创建一个超级简单的函数,它调用我也用 C 制作的应用程序,等待它完成,然后从应用程序接收返回值。

这是我的应用程序源代码:

int main(){
    return 777;
}

我编译它并将其重命名为 b.out 并将其放在根文件夹中,以便程序可以执行它。如您所见,应用所做的只是向系统返回 777。

这是调用应用程序的程序:

  #include <stdio.h>
  #include <string.h>
  #include <stdlib.h>
  #include <wait.h>
  #include <unistd.h>

  int rcode=0;

  int run(char* dir,char* mainapp,char *par1,char *par2){
  int f=fork();
  if (f==-1){
      printf("Fork call error\n");
      return -1;
  }
  if (f==0){ //child
      char cmdline[1000];
      memset(cmdline,0,1000); //command line = directory + / + appname
      strcat(cmdline,dir);
      strcat(cmdline,"/");
      strcat(cmdline,mainapp);
      //par1,par2 = parameters to program
      char *args[5]={cmdline,par1,par2,NULL};
      execve(cmdline,args,NULL);
      return 1; //this is child here
    }else{
      int waitstat;
      waitpid(f,&waitstat,0); //let child finish
      rcode=WEXITSTATUS(waitstat); //get return code from child
    }
  return 0;
  }

  int main(){
  if (run("/","b.out","","")==1){
      return 0; //exit if this is child
  };
  printf("Child returns %d\n",rcode); //only parent prints this
  return rcode;
  }

当我执行所有操作时,报告的返回值为 9 (rcode=9),但它应该等于 777,因为我的程序使它等于该值。

我应该用 exit(777) 替换 return 777 还是有更好的代码可以用来从孩子设置的孩子那里获取返回值?

【问题讨论】:

  • 退出代码为 8 位。如果将 777 截断为 8 位,则得到 9。
  • ^ 这对我来说是一个合理的答案
  • 我认为execve(cmdline, args, NULL); 是一个错误;您正在使用完全空的环境调用程序。 (更糟糕的是,您使用 NULL 指针调用它,而不是使用以 NULL 结尾的数组;空环境应该是由单个 NULL 组成的 char* 数组。)通常,程序不能使用完全空荡荡的环境,尽管您正在运行的程序当然什么也不做。但除非您有特定的安全问题,否则您通常希望通过使用 execv 将您的环境传递给新进程。
  • 并且:char cmdline[1000]; snprintf(cmdline, sizeof(cmdline), "%s/%s", dir, mainapp); 比所有 strcat 调用更安全、更快速、更易于阅读。 (但它需要一个功能测试宏:#define _XOPEN_SOURCE 700 应该这样做。)
  • man 3 退出。见说明。 The exit() function causes normal process termination and the value of status &amp; 0377 is returned to the parent.

标签: c linux fork return-value child-process


【解决方案1】:

退出代码为 8 位。

将 777 截断为 8 位得到值 9。

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 2019-08-04
    • 2020-10-04
    • 1970-01-01
    • 2018-09-09
    • 2010-12-23
    • 1970-01-01
    • 2012-02-20
    • 2016-11-17
    相关资源
    最近更新 更多