修改代码后,当客户端断开连接后,服务器端父进程收到子进程的SIGCHLD信号后,会执行sig_chld函数,对子进程进行了清理,便不会再出现僵尸进程。此时,一个客户端主动断开连接后,服务器端会输出类似如下信息:
child 12306 terminated
wait和waitpid
上述程序中sig_chld函数,我们使用了wait()来清除终止的子进程。还有一个类似的函数wait_pid。我们先来看看这两个函数原型:
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
官方描述:All of these system calls are used to wait for state changes in a child of the calling process, and obtain information about the child whose state has changed. A state change is considered to be: the child ter minated; the child was stopped by a signal; or the child was resumed by a signal. In the case of a terminated child, performing a wait allows the system to release the resources associated with the child; if a wait is not performed, then the terminated child remains in a "zombie" state (see NOTES below).
关于wait和waitpid两者的区别与联系:
The wait() system call suspends execution of the calling process until one of its children terminates. The call wait(&status) is equivalent to:
waitpid(-1, &status, 0);
The waitpid() system call suspends execution of the calling process until a child specified by pid argument has changed state. By default, waitpid() waits only for terminated children, but this behavior is modifiable via the options argument, as described below.
也就是说,wait()系统调用会挂起调用进程,直到它的任意一个子进程终止。调用wait(&status)的效果跟调用waitpid(-1, &status, 0)的效果是一样一样的。
waitpid()会挂起调用进程,直到参数pid指定的进程状态改变,默认情况下,waitpid() 只等待子进程的终止状态。如果需要,可以通过设置options的值,来处理非终止状态的情况。比如:
The value of options is an OR of zero or more of the following constants:
WNOHANG return immediately if no child has exited.
WUNTRACED also return if a child has stopped (but not traced via ptrace(2)). Status for traced children which have stopped is provided even if this option is not specified.
WCONTINUED (since Linux 2.6.10)also return if a stopped child has been resumed by delivery of SIGCONT.
等等一下非终止状态。
现在来通过实例看看wait()和waitpid()的区别。
通过修改客户端程序,在客户端程序中一次性建立5个套接字连接到服务器,状态如下图所示(附代码):