如何从同一个父级派生多个进程

How to fork multiple processes from a same parent?

本文关键字:派生 进程 同一个      更新时间:2023-10-16

我试图从同一个父级创建多个进程,但最终总是产生比预期更多的进程。我不知道该怎么做,需要一些帮助。

我在网上找到了一段代码并尝试了一下,

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循环中派生更多的孙进程。但我需要让这些孩子的程序运行一段时间,他们需要与父母沟通。

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

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
}