为什么在父进程调用 wait() 函数之前子进程没有退出?

Why child process not getting exited before parent process calls wait() function?

我正在开发使用 fork()wait() 调用的 c 程序,首先我创建了五个子进程,然后我调用了 wait() 五次。每当我执行该程序时,它都会在第二个 for 循环中打印相同的子进程 ID,该 ID 从第一个 for 循环显示。在调用 wait() 函数之前,子进程永远不会退出。为什么会这样?为什么 cpid 总是打印之前显示的确切子进程 ID?

代码:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main( )
{
    int child_pids[5];
    int i;
    printf("PARENT ID: %d \n", getpid());
    for(i=0;i<5;i++) {
        if(fork()==0) {
            printf("child(pid): %d of parent(pid): %d \n",getpid(),getppid());
            exit(0);
        }
    }
    for(i=0;i<5;i++) {
        int cpid=wait(NULL);
        printf("parent (pid): %d waited for child(pid): %d \n",getpid(),cpid);
    }
    return 0;
}

如果我提问的方式有什么错误,欢迎在下方评论

退出时,child 会留下一个应该返回给 parent 的退出状态。所以,当 child 完成时,它变成了僵尸。

每当 child 退出或停止时,parent 就会发送一个 SIGCHLD 信号。 parent 可以使用系统调用 wait()waitpid() 以及宏 WIFEXITEDWEXITSTATUS 来了解其已停止的状态 child.

如果 parent 退出,那么您可以看到您的 children 仍然是僵尸进程(未等待 children )。

wait() 只是告诉你哪个 child 退出了,所以你可以获得退出代码。如果你有更多 children 运行,那么当然,其他人也可能同时终止。

如果你不关心退出状态,那么wait()就好了,但你仍然需要等待你开始的所有children