【问题标题】:What is the correct way to make a parent process wait for its child processes?使父进程等待其子进程的正确方法是什么?
【发布时间】:2016-08-29 16:19:31
【问题描述】:

这是我写的程序

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<iostream>
#include<wait.h>
int main(void){
    std::cout << "My process " << getpid() << std::endl;
    int i;
    for(i=0;i<2;i++){
        int j = fork();
        wait(NULL);

        std::cout << "Process id :" << getpid() <<" and parent:"<< getppid()<< " and value returned is " << j <<std::endl;
    }
    return 0;
}

这是我得到的输出:

My process 5501
Process id :5502 and parent:5501 and value returned is 0
Process id :5503 and parent:5502 and value returned is 0
Process id :5502 and parent:5501 and value returned is 5503
Process id :5501 and parent:2828 and value returned is 5502
Process id :5504 and parent:5501 and value returned is 0
Process id :5501 and parent:2828 and value returned is 5504

有人可以向我解释一下输出吗?该程序的目的是以 DFS 方式“访问”进程。但是,我不明白第三行中返回的值是 5503 的原因,以及为什么即使我只运行了两次循环,是否会创建 5504?提前致谢。

【问题讨论】:

  • 你了解fork的操作吗?
  • 问题与c++无关
  • @OliverCharlesworth 是的,我愿意
  • 那你为什么在调用fork之后又无条件地调用wait
  • 目的是让父进程等到其子进程终止。我在这里读到了 [stackoverflow.com/questions/19461744/…

标签: c linux unix process


【解决方案1】:

5503 被返回给调用 fork() 的父级,因为在父级中,fork() 返回它新创建的子级的 PID,而在子级中,0 被返回。所以你需要对fork()的返回值做一个if来测试你是在父还是子中,这样你就可以只在你想要的那个中运行后续代码,否则它将在两者中运行。

至于您问题的第二部分,您需要在forking 之前检查您是否在父母(或孩子,取决于您要创建第二个孩子的人)中(并且等待 - 只等待parent) 再次(for 循环的第二次迭代);如果你不这样做,父母和孩子(从第一次在第一次迭代中调用它)都会调用fork(),并各自创建另一个孩子。这就是父级创建5504 的原因。

【讨论】:

  • 支票故意不存在。我意识到我的错误。我很困惑,忘记跟踪每个 fork 的原始父进程。无论如何感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-24
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 2013-12-17
相关资源
最近更新 更多