首先,在父线程程序中注册对于子线程的中止信号的监听
即使用如下一行代码:
signal(SIGCHLD,sigchld);
这行代码必须写在子线程创建之前
以下是信号处理函数,它负责子线程资源的回收
static void sigchld(int sig)
{
pid_t pid;
int status;
/* Reap defunct children until there aren't any more. */
for (;;) //循环非阻塞,取出死进程清理
{
pid = waitpid( (pid_t) -1, &status, WNOHANG ); //-1表示第一个中止的子进程,WNOHANG表示非阻塞
if (pid==0) //没有有待回收的了
break;
if (pid<0)
{
/* because of ptrace */
if (errno==EINTR)
continue;
break;
}
}
}
该程序可以防止多个子线程同时中止时的回收遗漏