Warm tip: This article is reproduced from serverfault.com, please click

c-如何为矩阵的每个元素创建一个新过程?

(c - How can I create a new process for each element of a matrix?)

发布于 2020-12-21 21:32:35

我想创建一个矩阵,其中每个单元格都包含一个进程(稍后将执行一些必需的操作)。此刻,我只想打印显示每个进程的PID的矩阵,但是使用fork()函数,我不断得到一个无限循环。我可能不了解fork函数如何工作。谁能向我解释它的工作原理,甚至可以给我一些有关我刚才提出的案例的例子?提前致谢!

pid_t forking;
for (int i = 0; i < ROW; i++){
    for (int j = 0; j < COL; j++){
            forking = fork();
            exit(EXIT_SUCCESS);
    }
}
Questioner
Chiara Tumminelli
Viewed
0
Some programmer dude 2020-12-22 07:01:35

现在,当我们看到一些代码时,我的猜测似乎是正确的。如果你似乎误解了fork工作原理...

如果成功,它实际上会返回两次!一次在父进程中,一次在子进程中。在子进程中,你不应继续循环,而应先进行一些“工作”,然后再进行exit父进程应继续循环以创建进程,然后执行其自身的处理,然后才能最终获得所有子进程。

简而言之:

pid_t pid_matrix[ROW][COL];

for (size_t row = 0; row < ROW; ++row)
{
    for (size_t col = 0; col < COL; ++col)
    {
        pid_matrix[row][col] = fork();

        if (pid_matrix[row][col] == -1)
        {
            // Error! Handle it some nice way
        }
        else if (pid_matrix[row][col] == 0)
        {
            // In the child process...
            // TODO: Do some work here!
            printf("In a new child process with pid %d\n", getpid());

            exit(EXIT_SUCCESS);  // Terminate the child process

            // Note that because the child-process have now exited,
            // the loop will not continue
        }
        else
        {
            // In the parent process
            printf("Created a new process with pid %d\n", pid_matrix[row][col]);

            // Note that we don't exit or do anything special here
            // This will let the loops continue as normal
        }
    }
}

[如何获得(释放资源)子进程作为练习留给读者]