COMMENTS

  • james@rounter: Hey okay thx. :)
  • james@router: Does my mac adresse change if I upgrade my computer with some...
  • Firm: 这方面没接触过 8-O
  • ontogma: итак: восхитительно… Киев лучшие секс знакомства...
  • 一路阳光: 现在再看刚毕业时的简历肯定感觉有点心虚,当年要不是初生牛犊估 计也没有那份胆量写那样的简历了
  • licream: 我也离了。0 0。不过还没找上。郁闷哦
  • Firm: 公司面试都喜欢考链表 确实,俺上次也考这个了
  • bokit: 今天第一天开工,祝心想事成,顺顺利利 PS:恭喜博主,新的一年新的开始。

使用setitimer和signal创建一个计时器

无聊之中,学习了一下setitimer函数的使用,整理一下,做个记录。

getitimer,setitimer – get or set value of an interval timer,man的第一句话是这样写的。其中的用法写的很详细了。

函数原型: setitimer(int which,const struct itimerval *value,struct itimerval *ovalue)

  • 参数一表示了计时器的类别,共分3种

<!—摘自网络

ITIMER_REAL:减少实际时间.到时的时候发出SIGALRM信号。

ITIMER_VIRTUAL:减少有效时间(进程执行的时间).产生SIGVTALRM信号。

ITIMER_PROF:减少进程的有效时间和系统时间(为进程调度用的时间)。这个经常和上面一个使用用来计算系统内核时间 和用户时间.产生SIGPROF信号。

————–>

  • 参数二是itimerval结构指针,对于itimerval我们需要定义
  • itimerval.it_value.tv_sec,

    itimerval.it_value.tv_usec,

    itimerval.it_interval.tv_sec,

    itimerval.it_interval.tv_usec,

分别表示了第一次执行时间,单位s;第一次执行时间,单位ms;间隔时间,单位s,间隔时间,单位ms。

计时器是递减的,时间到零后触发signal。下边的小程序运行5s后输出第一个hello!!,以后每隔一秒输出一次hello!!

供大家参考
timer.h

1
2
3
4
5
6
7
8
#ifndef TIMER_H
#define TIMER_H
 
struct itimerval tval;
void settimer(unsigned int,unsigned int,unsigned int,unsigned int);
void msg();
void quite();
#endif

timer.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <sys/time.h>
#include "timer.h"
 
int main()
{
  settimer(5,0,1,0);
  signal(SIGALRM,msg);
  signal(SIGINT,quite);
 
  for(;;);
  return 0;
}
 
void msg()
{
  printf("hello world!!\n");
}
void quite()
{
  printf("received interrupt[CTRL+C] signal,exit process!\n");
  exit(0);
}
void settimer(unsigned int ue_sec,unsigned int ue_usec,unsigned int val_sec,unsigned int val_usec)
{
  int res=0;;
  memset(&tval,0,sizeof(tval));
 
  tval.it_value.tv_sec=ue_sec;
  tval.it_value.tv_usec=ue_usec;
  tval.it_interval.tv_sec=val_sec;
  tval.it_interval.tv_usec=val_usec;
  tval=tval;
  res=setitimer(ITIMER_REAL,&tval,NULL);
  if(res)
     {
    printf("set timer failed!\n");
    }
}
相关文章:
  1. MD5应用的一点理解及Linux实现源码
  2. 使用原始套接字SOCK_RAW捕捉网络数据包并简单分析
  3. strftime和strptime使用
  4. Linux多线程(1)
  5. 一种IP改变唤醒SNMP TRAP的实现源码

2 comments to 使用setitimer和signal创建一个计时器

Leave a Reply

 

 

 

:wink: :twisted: :roll: :oops: :mrgreen: :lol: :idea: :evil: :cry: :arrow: :?: :-| :-x :-o :-P :-D :-? :) :( :!: 8-O 8)