struct itimerval
{
/* Value to put into `it_value' when the timer expires. */
struct timeval it_interval;
/* Time to the next timer expiration. */
struct timeval it_value;
};
it_interval:计时器的初始值,一般基于这个初始值来加或者来减,看控制函数的参数配置
it_value:程序跑到这之后,多久启动定时器
struct timeval
{
__time_t tv_sec; /* Seconds. */
__suseconds_t tv_usec; /* Microseconds. */
};
int setitimer (__itimer_which_t __which,
const struct itimerval *__restrict __new,
struct itimerval *__restrict __old)
分析:
1、调用itimerval这个结构体成员
t_interval:计时器的初始值,一般基于这个初始值来加或者来减,看控制函数的参数配置
it_value:程序跑到这之后,多久启动定时器
2、itimerval结构体成员调用时间戳结构体timeval来配置
3、t_interval配置好了以后需要通过setitimer来实现减的功能(成功执行时,返回0。失败返回-1)
1.__itimer_which_t __which代表减的方式和返回不同的信号
ITIMER_REAL //数值为0,计时器的值实时递减,发送的信号是SIGALRM。
ITIMER_VIRTUAL //数值为1,进程执行时递减计时器的值,发送的信号是SIGVTALRM。
ITIMER_PROF //数值为2,进程和系统执行时都递减计时器的值,发送的信号是SIGPROF。
2.const struct itimerval *__restrict __new指向itimerval这个结构体
3.struct itimerval *__restrict __old一般设置为空
隔一秒就发送一句hello的代码:
1 #include <stdio.h>
2 #include <sys/time.h>
3 #include <stdlib.h>
4 #include <signal.h>
5 static int i = 0;
6 void signal_handler(int signum)
7 {
8 i++;
9 if(i == 2000){//一次是500ms,2000次刚好就是一秒,实现一秒打印一次
10 printf("hello!\n");
11 i = 0;
12
13 }
14
15
16 }
17
18 int main ()
19 {
20 struct itimerval itv;
21 //设定程序跑到这里以后需要等待开启定时器的时间为1s
22 itv.it_value.tv_sec = 1;
23 itv.it_value.tv_usec = 0;
24 //设定需要减少的时间为500ms
25 itv.it_interval.tv_sec = 0;
26 itv.it_interval.tv_usec = 500;
27
28 //设定递减的方式
29 if(setitimer(ITIMER_REAL,&itv,NULL) == -1)
30 {
31 perror("error");
32 exit(-1);
33 }
34
35 //信号处理
36 signal(SIGALRM,signal_handler);
37
38 while(1);
39
40
41 return 0;
42 }
~
