#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]#