Linux wait and Waitpid

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.