在之前我们为了避免出现僵尸进程我们采用了两种方式
1、调用wait()函数使父进程去等待子进程。wait()是一种阻塞等待
2、调用waitpid()函数这也是父进程去等待子进程而waitpid()分为阻塞式等待和非阻塞式等待,轮询的方式就是建立在非阻塞等待的基础之上的
而SIGCHLD信号也可以避免出现僵尸进程
创建僵尸进程
#include<stdio.h>
#include <unistd.h>
int main()
{
int i=0;
if(fork()==0)
{
printf("i am child:%d\n",getpid());
}
else
{
sleep(2);
system("ps -o pid,ppid,state,tty,command");
printf("i am father:%d\n",getpid());
}
return 0;
}
使用wait来解决僵尸进程
方式一:
采用wait()函数去等待
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
int i=0;
if(fork()==0)
{
printf("i am child:%d\n",getpid());
}
else
{
sleep(2);
wait(NULL);
system("ps -o pid,ppid,state,tty,command");
printf("i am father:%d\n",getpid());
}
return 0;
}
发送一个SIGCHLD信号
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<signal.h>
void myhandler(int sig)
{
printf("i am get a sig:%d\n",getpid());
wait(NULL);
}
int main()
{
int i=0;
signal(SIGCHLD,myhandler);
if(fork()==0)
{
printf("i am 1child:%d\n",getpid());
}
else
{
sleep(2);
system("ps -o pid,ppid,state,tty,command");
printf("i am father:%d\n",getpid());
}
system("ps -o pid,ppid,state,tty,command");
return 0;
}
但是这样只处理了一个僵尸进程
假如有多个僵尸进程呢,因为收到多个信号,但是只记录一次因此需要循环回收.
因为如果是9个子进程都退出了,还有一个没有退出,但必须也要在最后一个退出的时候给父进程发送一个SIGCHLD信号,因此要是非阻塞的
#include<stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include<signal.h>
void myhandler(int sig)
{
printf("i am get a sig:%d\n",getpid());
int status;
while(waitpid(-1, &status, WNOHANG) > 0);
}
int main()
{
int i=0;
signal(SIGCHLD,myhandler);
if(fork()==0)
{
printf("i am 1child:%d\n",getpid());
}
else
{
sleep(2);
system("ps -o pid,ppid,state,tty,command");
printf("i am father:%d\n",getpid());
}
system("ps -o pid,ppid,state,tty,command");
return 0;
}