WNOHANG 是否清理 child 资源

Does WNOHANG clean child resources

我正在尝试了解使用 WNOHANG 的 waitpid() 如何以及确实清理了它应该等待的 child 的资源?

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {

        printf("Hello from start\n");

        int pid;

        if((pid = fork()) == 0){
                printf("Hello from child: %d\n", getpid());
                printf("My parent PID is: %d\n", getppid());
        }else if(pid > 0){
                printf("Hello from parent: %d\n", getpid());
                int status;
                waitpid(pid, &status, WNOHANG);
        }else{
                perror("ERROR");
        }

        printf("Outside if statement, pid is: %d\n", getpid());


}

parent PID 的 child 进程的输出是:1 意味着 parent 终止并且 child 是僵尸传递给 init 进程。

根据我对 man 描述中 WNOHANG 的理解,它应该 return 在测试它时 child 进程是否终止并让 parent 进程继续。然而,我认为如果 parent 即将在其 child 之前终止,它将等待 child 来“清理它”。由此看来 parent 只是继续运行并在没有清理的情况下终止。

我错过了什么,如何让 parent 继续它的工作而不让它在不等待 child 先终止的情况下终止?

谢谢!

I however thought that if parent was about to terminate before its child, it would wait for child to "clean it up".

事实并非如此。 parent 不会等待。终止的进程的 Children 重新parent 到进程 1,它们将在终止时自动获得。

how to let parent continue its work but not let it terminate without waiting for child to terminate first?

work();

int status;
waitpid(pid, &status, 0);