繁体   English   中英

如何从同一个父进程 fork 多个进程?

[英]How to fork multiple processes from a same parent?

我正在尝试从同一个父进程创建多个进程,但它最终总是比预期的进程多。 我不知道该怎么做,需要一些帮助。

网上找了一段代码试了一下,

int main ()
{
    pid_t pid=0;
    int i=0;
    for (i=0; i<3; i++)
    {
        pid=fork();
        switch(pid)
        {
            case 0:
            {
                cout<<"\nI am a child and my pid is:"<<getpid();
                cout<<endl;
                exit(0);
                break;
            }
            default:
            {
                cout<<"\nI am a parent and my pid is: "<<getpid();
                cout<<"\nMy child pid is: "<<pid;
                cout<<endl;
                wait(NULL);
                break;
            }
        }
    }
  return 0;
 }

此代码确实有效并从同一个父级创建了 3 个子级。 然而,这似乎是因为每个子进程创建后,它立即终止。 所以它不会在下一轮 for 循环中 fork 更多的孙进程。 但我需要让这些子进程运行一段时间,他们需要与父母沟通。

子进程可能会立即中断循环以在外部继续工作

int main ()
{
   cout<<"\nI am a parent and my pid is: "<<getpid()<<endl;

   pid_t pid;
   int i;
   for (i=0; i<3; i++)
   {
       pid=fork();
       if(pid == -1)
       {
           cout<<"Error in fork()"<<endl;
           return 1;
       }
       if(pid == 0)
           break;
       cout<<"My child "<<i<<" pid is: "<<pid<<endl;
    }

    if(pid == 0)
    {
        cout<<"I am a child  "<<i<<" and my pid is "<<getpid()<<endl;
        wait(NULL);  // EDIT: this line is wrong!
    }
    else
    {
        cout<<"I am a parent :)"<<endl;
        wait(NULL);  // EDIT: this line is wrong!
    }
    return 0;
}

编辑
wait(NULL)行是错误的。 如果进程没有处于活动状态的子进程, wait()没有作用,所以这里的子进程没有用。 父进程wait()中的 OTOH 暂停执行,直到任何子进程退出。 我们这里有三个孩子,所以必须wait()三次。 此外,我们无法提前知道子项完成的顺序,因此我们需要更复杂的代码。 像这样的东西:

struct WORK_DESCRIPTION {
    int    childpid;
    // any other data - what a child has to do
} work[3];

for(i=1; i<3; i++) {
    pid=fork();
    ...
    work[i].childpid = pid;
}

if(pid == 0)    // in a child
{
    do_something( work[i] );
}
else
{
    int childpid;
    while(childpid = wait(NULL), childpid != 0)
    {
        // a child terminated - find out which one it was

        for(i=0; i<3; i++)
            if(work[i].childpid == childpid)
            {
                // use the i-th child results here
            }
    }
    // wait returned 0 - no more children to wait for
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM