上篇讲到僵尸进程产生的原因及危害,并且简要的提到了避免产生僵尸进程的两种方法:
一、让父进程先退出,形成孤儿进程,最终由1号进程(init进程)来回收子进程系统资源;
二、父进程调用wait、waitpid函数,以阻塞或非阻塞轮训的方式来等待子进程退出,并回收子进程的系统资源;
本篇将具体来讲解一下,两种解决方案的具体实施过程。
一、避免僵尸进程之 ✈✈✈✈ 形成孤儿进程
《Unix 环境高级编程》8.6节
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, const char *argv[])
{
pid_t pid;
//创建第一个子进程
if ( (pid = fork()) < 0)
{
perror("fork error:");
exit(1);
}
//第一个子进程
else if (pid == 0)
{
printf("I am the first child process.pid:%d\tppid:%d\n",getpid(),getppid());
//在子进程内创建第二个子进程(即孙子进程)
if ( (pid = fork()) < 0)
{
perror("fork error:");
exit(1);
}
else if (pid >0)
{
//第一个子进程退出
printf("first procee is exited.\n");
exit(0);
}
//从这开始就是孙子进程的天下了
//睡眠3s保证孙子进程的父进程(第一个子进程)退出,这样孙子进程就会被1号进程所收养,形成孤儿进程
sleep(3);
printf("I am the second child process.pid: %d\tppid:%d\n",getpid(),getppid());
exit(0);
}
//父进程处理第一个子进程退出,注意子进程的pid在父进程中返回,所以在这直接等待pid的退出;
if (waitpid(pid, NULL, 0) != pid)
{
perror("waitepid error:");
exit(1);
}
exit(0);
return 0