C - 使子进程等待另一个 for 循环



我已经在谷歌上搜索我的问题 2 天了,但我完成了。我有关于流程管理、分叉等的非常基本的信息。我被告知要创建同一父进程的一些子进程,并使用管道向它们发送种子,以便它们可以生成一些随机数,所有这些都是为了他们自己的。但是我坚持创建子进程。

for (i = 0; i < NUM_PLAYERS; i++) {
    /* TODO: spawn the processes that simulate the players */
    switch(pid = fork()){
        case -1:  // ERROR
            exit(EXIT_FAILURE);
        case 0:  // CHILD PROCESS
            printf("My parent id is %d n", getppid());
            exit(EXIT_SUCCESS);
        default: // PARENT PROCESS
            wait(NULL);
    }
}

当我使用此代码时,parent 会创建NUM_PLAYERS子项,但我似乎无法在另一个 for 循环中使用它们,因为它们在案例 0 结束时终止。当我删除exit(EXIT_SUCCESS);行时,会创建许多进程,并且它们具有不同的父级。所以我的问题是,如何正确创建子进程并在以后使用它们?

如果您删除exit(EXIT_SUCCESS)您的孩子将继续在分叉的地方执行,IE 它将返回到 for() 循环的紧密支撑,并自己生成新的子项。你想让孩子做什么?你应该让它这样做,然后做exit(EXIT_SUCCESS),不要让它返回到for()循环。

另请注意,wait()只会等待一个进程退出。

void do_something()
{
    //create random numbers or whatnot
}
/

/.....

case 0:  // CHILD PROCESS
    printf("My parent id is %d n", getppid());
    do_something();
    exit(EXIT_SUCCESS);

您需要家长在稍后的循环中wait子项。 你拥有它的方式会阻止,直到一个孩子回来。 您希望先创建多个子项,然后再对它们进行wait

请注意,您仍然必须添加管道逻辑,以便父/子级可以进行通信。

编辑

以下是您需要执行的操作的大致轮廓:

for (i = 0; i < NUM_PLAYERS; i++) {
    /* TODO: spawn the processes that simulate the players */
    switch(pid = fork()){
        case -1:  // ERROR
            exit(EXIT_FAILURE);
        case 0:  // CHILD PROCESS
            printf("My parent id is %d n", getppid());
            exit(EXIT_SUCCESS);
    }
}
// only the parent will ever execute below here
for (i = 0; i < NUM_PLAYERS; i++) 
{
    while ( /* read each child's pipe*/)
    {
        //do something with data
    }
}
for (i = 0; i < NUM_PLAYERS; i++) 
    wait(NULL);
return(0);

最新更新