曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 5517|回复: 0
打印 上一主题 下一主题

getitimer()/setitimer() -- 获得/设置内部间隔定时器值

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34395
跳转到指定楼层
楼主
发表于 2011-4-6 17:37:34 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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
      ITIMER_VIRTUAL
      ITIMER_PROF
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 这样的结构体中。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2025-5-6 08:13 , Processed in 0.080715 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表