为什么我的 parent 没有等待每个 child?

Why is my parent not waiting for each child?

为什么这个程序不等待所有children?当 parent 的 wait(NULL) 认识到所有 children 已完成时,总有 2 个未完成。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>

void foo(int* pointer) {
    //some code...
    return;
}



int main() {
    //some vars
    int var = 0;
    int *pointer = &var;
    pid_t pid = 0;
    
    
    //create 10 children
    for(int i = 0; i < 10; i++) {
        pid = fork();
        if(pid == 0) { 
            foo(pointer);
            printf("back from foo()\n");
            //exit(0);              //do I need exit(0) here to terminate all children??? or just return ?
            return 0;
        }
    }
    
    printf("waiting for children...\n");
    wait(NULL);                             
    printf("all children finished...\n");   
    return 0;
}

输出总是如下:

back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
back from foo()
waiting for children...
all children finished...
back from foo()
back from foo()

有些 children 在创建所有 children 之前从 foo 返回是可以理解的,但是为什么当 parent 停止等待时有些仍在工作?我是否在每个 children 处使用 exit(0); or/and return 0; 搞砸了?

提前致谢! <3

来自 man wait(注意:“其中之一”部分):

The wait() system call suspends execution of the calling thread until one of its children terminates.

在代码的注释中,你问:

// do I need exit(0) here to terminate all children or just return?

鉴于代码在main()中,return(0);exit(0);是等价的。在任何其他函数中,几乎可以肯定您需要 exit(0);。就个人而言,我也会在 main() 中使用 exit(0);,以防止将来将代码移至另一个函数的更改。并注意 exit(0): 仅终止当前进程,这是一个 child 进程,给定 exit(0); 调用将被放置的位置。

wait() 函数等待单个 child 终止。您必须使用循环等待所有 children:

int corpse;
int status;
while ((corpse = wait(&status)) > 0)
    print("Child %d exited with status 0x%.4X\n", corpse, status);

你问:

Have I messed something up with the usage of exit(0); or/and return 0; in each child?

不:你没有在循环中使用 wait() 搞砸了。

如果您熟悉 shell 的 wait 命令,您可能知道它会等待所有 child 进程终止。 wait() 系统调用不同于 shell 命令。