C 中的 fork() 和 exit()

fork() and exit() in C

我试图理解以下内容,其中只有 child 进程在创建 children.

int main(int argc, char **argv) {
    int i;
    int n;
    int num_kids;

    if (argc != 2) {
        fprintf(stderr, "Usage: forkloop <numkids>\n");
        exit(1);
    }

    num_kids = atoi(argv[1]);

    for (i = 0; i < num_kids; i++) {
        n = fork();
        if (n > 0) {
            printf("pid = %d, ppid = %d, i = %d\n", getpid(), getppid(), i);
            if (wait(NULL) == -1) {
                perror("wait");
            }
            exit(0);
        } else {
            printf("pid = %d, ppid = %d, i = %d\n", getpid(), getppid(), i);
        }
    }
    return 0;
}

我的理解是否正确,在每个循环结束时,parent 进程退出,child 成为新的 parent?原因是exit()语句,它终止了parent进程?此外,parent 中的 wait() 是否等待其 child 终止,循环的每次迭代然后才退出?但是,child 永远不会真正退出,那么 wait 语句什么时候开始起作用?

Am I right in understanding that, at the end of every loop, the parent process exits, and the child becomes the new parent? The reason is the exit() statement, which terminates the parent process?

是的,但进程不会立即终止。每个 "parent" 调用 wait() 并等待子进程完成。

Also, does wait() in the parent, wait for its child to terminate, every iteration of the loop and only then exit?

是的。这意味着 "parent" 进程以相反的顺序死亡。这意味着第一个进程最后死亡。

But, then the child never really exits, so when does the wait statement come into play?

所有进程都在您的代码中终止。当第一个子进程继续执行 for 循环时,父进程等待(同样所有其他子进程等待它们的子进程)。最后一个进程因退出循环而死亡,并通过 main() 返回退出。