恕我直言,您的代码是正确的:
Upon successful completion, fork() returns a value of 0 to the child
process and returns the process ID of the child process to the parent
process. Otherwise, a value of -1 is returned to the parent process, no
child process is created, and the global variable errno is set to indi-
cate the error.
但可能它没有达到您的预期,如果所有分叉都成功,它会创建 2^num_fork_loops。如果分叉失败,它会返回 -1 并且您检查返回值是正确的,但如果成功,它会返回 0孩子和父亲的PID(始终为正),因此在这种情况下,子进程也将开始创建其他进程。
通过使子进程执行其他操作来更正代码(除非您想要 2^N 个进程):
for(j = 0; j < num_fork_loops;j++) {
pid_t pid=fork();
if (pid < 0)
{
printf("Fork has failed\n");
exit(EXIT_FAILURE);
}
else if(pid==0)
{
j=num_fork_loops; // avoid to continue the loop for the child
child_routine();
}
else
{
// This is the father, in case of success of the fork
j++;
}
}