Does WNOHANG clean child resources

Viewed 93

I am trying to understand how and does waitpid() using WNOHANG actually clean the resources of the child it's supposed to wait for?

#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());


}

The output for child process for parent PID is: 1 meaning parent terminated and child was zombie passed to init process.

From what I understood WNOHANG in man description, it's supposed to return whether child process terminated at the time of testing it and let parent process continue on. I however thought that if parent was about to terminate before its child, it would wait for child to "clean it up". From this it seems that the parent just keeps on going and terminates without cleaning up.

What am I missing, and how to let parent continue its work but not let it terminate without waiting for child to terminate first?

Thanks!

1 Answers

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

That is not the case. The parent won't wait. Children of a process that terminates get reparented to process 1, and they will automatically get reaped when they terminate.

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);
Related