linux 信号sigaction 与 pause ,alarm 练习

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
void catch_sigalarm()
{
   printf("ALARM was catched\n");
}
int mysleep(int seconds)
{

   int ret ;
   struct sigaction act ,oldact;

   act.sa_handler =  catch_sigalarm;
   sigemptyset(&act.sa_mask);   //初始化屏蔽字
   act.sa_flags = 0 ;
   ret = sigaction(SIGALRM ,&act ,&oldact);  //设置对时钟信号捕捉
   alarm(seconds);
   ret  = pause();
   if(ret == -1 && errno ==EINTR )
   {
      printf("pause success\n");
   }
   alarm(0);  //清除时钟
   sigaction(SIGALRM ,&oldact , NULL);//返回旧有的信号屏蔽字
   return ;
}

int main()
{
   while(1)
   {
      mysleep(3);
      printf("----------\n");
   }
   return 0;
}

首先,注意一点,就是 sa_mask ,我们可以通过sa_mask ,来控制程序在遇到信号时,进行相应处理。在信号处理函数执行过程中,如果有其他信号,这时sa_mask就可以设置相应信号的字屏蔽,防止信号处理函数被中断。本例子中未设置sa_mask。

运行结果:

ALARM was catched
pause success
----------
ALARM was catched
pause success
----------
ALARM was catched
pause success
----------
ALARM was catched
pause success
----------
^C
 

 

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
void catch_sigalarm()
{
   printf("ALARM was catched\n");
}
int mysleep(int seconds)
{

   int ret ;
   struct sigaction act ,oldact;

   act.sa_handler =  catch_sigalarm;
   sigemptyset(&act.sa_mask);
   act.sa_flags = 0 ;
   
   ret = sigaction(SIGALRM ,&act ,&oldact);
   
   alarm(seconds);  //只在本栈能用;
   ret  = pause();
   if(ret == -1 && errno ==EINTR )
   {
      printf("pause success\n");
   }
  // alarm(0);
   sigaction(SIGALRM ,&oldact , NULL);
   return ;
}

int main()
{
  
      mysleep(3);
      printf("----------\n");
      pause();
      signal(SIGALRM , catch_sigalarm);

   return 0;
}

结果:alarm 不影响主函数

[root@localhost singal]# ./sig1
ALARM was catched
pause success
----------
^C
[root@localhost singal]# 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值