先看代码:例1,alarm()
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
void alarm_handler(int sig)
{
printf("hello!--sig:%d\n",sig);
alarm(1);
}
int main()
{
if (signal(SIGALRM, alarm_handler) == SIG_ERR) { //安装信号,SIGALRM的编号为14
perror("signal");
return 0;
}
alarm(1);
while(1) { //让进程一直存在
pause();
}
return 0;
}
结果:
[lgh@localhost test]$ ./a.out
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
hello!--sig:14
---------------------------------------------
它会每秒打印一行"hello!--sig:14".
应用:使进程定期性地做某些操作.例如,给低速的IO操作给个时间上限,定期查看进程是否存在,连接是否中断等.
例2:setitimer(),这个比alarm()强大,可以有3种模式进行计数.
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>