SIGCHLD handling in C socket programming

13 views Asked by At

I'm reading Beej's Guide to Network Programming, mainly the section called 'A Simple Stream Server'. The author uses fork() to create child processes that send responses to clients. To prevent these child processes from being in the zombie state after termination, the author registers a SIGCHLD handler where the waitpid() function call is located. The code of the handler is presented below:

void sigchld_handler(int s)
{
    (void)s;

    int saved_errno = errno;

    while(waitpid(-1, NULL, WNOHANG) > 0);

    errno = saved_errno;
}

I understand it this way: when the state of a child changes, the SIGCHLD signal is emitted, and the handler is called. If the child process isn't terminated, then the waitpid() function call returns 0, and the loop is ignored. If there is a terminated child, then the waitpid() function returns the ID of the process, and the execution enters the loop and proceeds to the next iteration. If there is another terminated child, then the process repeats itself; otherwise, the execution leaves the loop.

I guess that I understand the code, but I don't understand the necessity of the loop. As I understand it, a signal will be emitted for each child which changed state, so the handler will eventually be called for each such change of the state. Why do we need to use this loop? Is it necessary for some reason? Is it beneficial?

A link to the full snippet of code is here.

0

There are 0 answers