This question was migrated from Unix & Linux Stack Exchange because it can be answered on Stack Overflow. Migrated四年前。Learn more
我试图从同一个父进程创建多个进程,但它总是以超出预期的进程结束。我不知道怎么做,需要帮助。
我在网上找到一段代码并试过了,

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暂停执行,直到任何一个孩子退出。我们这里有三个孩子,所以得三次。另外,我们不能提前知道孩子们完成的顺序,所以我们需要更复杂的代码。像这样的:
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
}

关于linux - 如何从同一个父节点派生多个进程?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27182511/

10-12 14:58
查看更多