Background: When reading UNIX Network programming volume 1, the fifth chapter server processes SIGCHLD signals. and multiple clients shutting down the socket connection at the same time, multiple sub-processes of the service-side master process end almost simultaneously.
Use the wait condition:
void sig_chld (int signo) { pid_t pid; int stat; = Wait (&stat); return ;}
When the server uses concurrent processing of client requests, the client process closes the connection, the service terminal process ends almost simultaneously, and the signal processing function does not completely prevent the zombie process from appearing when using wait, the problem is that the signal processing function, when processing the SIGCHLD signal of the first process, The next four processes also send a SIGCHLD signal, but the signal is not queued, which causes the signal to be lost, resulting in a lot of zombie processes. The solution in the book is to use the waitpid cycle to judge.
Using Waitpid:
void sig_chld (int Signo) {pid_t pid; int stat; while ((PID = waitpid (-1 , & Stat, Wnohang)) > 0 ) {printf ( " child%d terminated\n " , PID); return
See this code, began to fall into confusion, during the execution of SIG_CHLD, the signal behind is not also ignored it? Why can I prevent the zombie process? That's not true, Waitpid. When the first parameter is-1, it means waiting for any child process, and the parameter Wnohang represents a non-blocking wait. The function loops through all the sub-processes, and the man manual's return value on the function is also very clear, and if successful, returns the ID of the child process. Returns 0 when Wnohang is specified and there is one or more child processes still present and the process state has not changed. So as soon as the sig_chld is triggered, it loops until all the child processes are processed.
Linux wait and Waitpid