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

问题描述 投票:0回答:1

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

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

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更多的孙进程。但我需要让这些子进程运行一段时间,并且它们需要与父进程进行通信。

linux c++ fork process
1个回答
0
投票

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

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()
没有任何作用,因此它对这里的子进程没有用处。父进程中的 OTOH
wait()
暂停执行,直到 any 子进程退出。我们这里有三个孩子,所以必须
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
}
© www.soinside.com 2019 - 2024. All rights reserved.