Linux下的SIGCHLD信号

在之前我们为了避免出现僵尸进程我们采用了两种方式
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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值