【问题标题】:Multiple forks does not work多个分叉不起作用
【发布时间】:2016-02-26 19:05:16
【问题描述】:

我正在尝试创建 5 个孩子和 1 个父母。但是父母会创建它们(至少 4 个。因为首先我们需要分叉)但它会创建一堆孩子。找不到我做错了什么。请问有什么办法吗?

child0=fork();//first process
if(child0>0)//Parent
{

    //Create children
    child1=fork();
    child2=fork();
    child3=fork();
    child4=fork();
    cout<<"i am child 0 "<<child0 <<"  ";
    cout<<"i am child 1 "<<child1;
    cout<<"i am child 2 "<<child2;
    cout<<"i am child 3 "<<child3;
    cout<<"i am child 4 "<<child4;
    wait(child0);
    wait(child1);
    wait(child2);
    wait(child3);
    wait(child4);
}
else if(child0<0)
{
    printf("fork() failed!\n");
    exit(1);
}
else
{
cout<<"i am child0";
    exit(0);
}

【问题讨论】:

  • 你执行了很多分叉而不检查返回的 id。很多孩子也在分叉更多的孩子。

标签: c++ c fork


【解决方案1】:

每次分叉后,您的进程数都会增加一倍。这是你的代码:

child1=fork(); // we have two now
child2=fork(); // each one of them forks - we have 4
child3=fork(); // 8
child4=fork(); // 16

你需要检查fork的返回值。当它为非0时,你在父节点中,并且可以再次分叉。如果它是 0,你是孩子,你不应该fork() - 应该做你孩子的家务。

当您检查返回值时,您不妨检查一下-1 - 这意味着fork() 失败。尽管看起来令人难以置信,但我知道发生这种情况的生产系统。

【讨论】:

    【解决方案2】:

    永远记住——当你执行 fork() 时,child 和 parent 都会再次从 fork() 语句的下一行开始执行。 fork() 在子进程中返回 0,在父进程中返回子进程的 PID。因此,在您的情况下,孩子和父母都再次分叉。您正在创建进程树。

    以这种方式做

    int pid;
    if((pid=fork())==0)
    {
      // Child Process
      printf("I'm child");
    }
    else
    {
       // Parent process
       // Again do fork() here
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-03
      • 1970-01-01
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多