return 来自 child 进程 c 的值

return value from child process c

我需要帮助 return 将 "status code" 从我的 child 程序返回到 parent,它将检查状态代码、打印代码并退出parent。这是针对 class 项目的,因此我将在此处放置一些相关代码,但出于显而易见的原因,我不会 post 整个项目。

我已经通过 exec 分叉并创建了 child 进程。 parent 做了一些花哨的数学运算,并使用命名管道将数据推送到 child 进程。 child 做了一些更花哨的数学运算。当我使用关键字时,child 需要 return 它在最后返回到 parent 的花哨数学的次数,parent 会看到这个, 打印出 returned 号,然后退出 parent。

    int status;
    pid_t child_id;
    child_id = fork();
    if (child_id == 0)
    {
            // put child code here
            exec(opens second process);
    }
     if (child_id < 0)
    {
            perror("fork failed\n");
            exit(EXIT_FAILURE);
    }

     while(child_id != 0)
     {
       //parent process
       //do fancy math stuff here
       // pipe
      //open pipe
      //converted math to "string" to pass to other program
      // use fprintf to send data to other program
      fprintf(fp,"%s",str);
      //close pipe
//**************************************************
//this block doesn't work, always returns 0
      if (WIFEXITED(status)){
            int returned = WEXITSTATUS(status);
            printf("exited normally with status %d\n",returned);
      }
//***************************************************
   return 0;

第二个 c 程序只是对管道的简单读取,做了一些更花哨的数学运算,并在我想要 return 数字的地方放置了 return 语句。

据我所知,有一种方法可以从 child 程序传递 return 值,但我似乎无法理解如何传递。我添加了一段我找到的代码,但我似乎无法让它工作。我读过它,但也许我遗漏了什么?

请忽略任何语法或结构问题。

您试图通过 WIFEXITED 函数读取 status,但您从未给它赋值。尝试读取未初始化的值会调用 undefined behavior.

您需要调用 wait 函数,它告诉父级等待子级完成并接收其 return 代码:

wait(&status);
if (WIFEXITED(status)){
      int returned = WEXITSTATUS(status);
      printf("exited normally with status %d\n",returned);
}