Search code examples
csignalssystemzombie-process

Reaping zombie processes via handler


The code written below is to handle the received signals and reap the zombies by the parent process "from System Programming course of CMU".

Q1. what is the rule of -1 "the first arg of the waitpid function"? should not we pass the pid of the zombie we are reaping instead?

Q2. For the loop here, does it check all zombies each time a signal received by any precedent zombie?

int ccount = 0;
void child_handler2(int sig)
{
int child_status;
pid_t pid;
while ((pid = waitpid(-1, &child_status, WNOHANG)) > 0) {
   ccount--;
   safe_printf("Received signal %d from process %d\n",sig, pid);
 }
}

void fork14()
have sent this signal
{
pid_t pid[N];
int i, child_status;
linux> ./forks 14
ccount = N;
signal(SIGCHLD, child_handler);
for (i = 0; i < N; i++)
   if ((pid[i] = fork()) == 0) {
      sleep(1); /* deschedule child */
      exit(0); /* Child: Exit */
   }

while (ccount > 0)
pause(); /* Suspend until signal occurs */
}

Solution

  • Q1. "-1" means to check for all child processes.

    Q2. when a child process dies, Kernel sends a message to its parent to reap it. And because the nature of signals receiving which cannot be queued "at most one can be received at a time" which may lead to discarding some later signals if received before the handler finishes handling the previous signal, and may not. So, we can't make sure that we will have N zombies at that time as some of them may have been handled automatically by the handler. That is why at each time we reap a zombie we check if there is another zombie to reap and reap it or (them). So, checking here is to prevent waiting for a child which has been reaped already to save the parent from freezing "if we let it waits for a reaped zombie".