getitimer() 和 setitimer() 分别用来获取和设置间隔定时器的值。
函数原型:
[C++] 纯文本查看 复制代码 #include <sys/time.h>
int getitimer(int which, struct itimerval *curr_value);
int setitimer(int which, const struct itimerval *new_value, struct itimerval *old_value);
其中 struct itimerval 结构定义为:
[C++] 纯文本查看 复制代码 struct itimerval {
struct timeval it_interval; /* next value */
struct timeval it_value; /* current value */
};
struct timeval 结构定义为:
[C++] 纯文本查看 复制代码 struct timeval {
long tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
上面的定时器中的时间值分别为秒和微妙。
第 1 个参数 which 有 3 个值:
ITIMER_REAL 定时器的值是实时递减的,也就是说不管进程是处于任何状态(运行态或者睡眠态)这个值都会一直递减变化,当减至 0 时,发出 SIGALRM 信号。
ITIMER_VIRTUAL 定时器只有在进程运行时才会减,当超时发出 SIGVTALRM 信号。
ITIMER_PROF 进程和系统运行时定时器都会递减,在超时时发出 SIGPROF 信号。
在 struct itimerval 结构中,it_value 是一个初始值,it_interval 是一个在超时后自动填充的间隔值。也就是说,如果设置了it_value,那么当 it_value 减完就会一直用 it_interval 值来填充定时器。下面是 setitimer() 函数的使用示例:
[C++] 纯文本查看 复制代码 #include <sys/time.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
struct itimerval interval;
struct sigaction act;
void handler_sigvalrm (int signo)
{
//getitimer (ITIMER_VIRTUAL, &curr_value, NULL);
static i = 0;
if (!i) {
printf ("First, after 10s... \n");
getitimer (ITIMER_VIRTUAL, &curr_value);
}
else
printf ("3s after...\n");
i++;
if (i == 5)
exit (0);
}
int main()
{
act.sa_handler = handler_sigvalrm;
interval.it_interval.tv_sec = 3;
interval.it_interval.tv_usec = 0;
interval.it_value.tv_sec = 10;
interval.it_value.tv_usec = 0;
sigaction (SIGVTALRM, &act, NULL);
setitimer (ITIMER_VIRTUAL, &interval, NULL);
while (1);
return (0);
}
运行输出:
[beyes@SLinux system]$ ./gsetitimer
First, after 10s...
3s after...
3s after...
3s after...
3s after...
getitimer() 函数运行后可以获得定时器的当前值,它只是将获得的当前值填充到 struct itimerval 这样的结构体中。 |