setitimer()为Linux的API,并非C语言的Standard Library,setitimer()有两个功能,一是指定一段时间后,才执行某个function,二是每间格一段时间就执行某个function,以下程序demo如何使用setitimer()。
view plaincopy to clipboardprint?
01./*
02.
03.
04.
05.Filename : timer.cpp
06.
07.Compiler : gcc 4.1.0 on Fedora Core 5
08.
09.Description : setitimer() set the interval to run function
10.
11.Synopsis : #include <sys/time.h>
12.
13. int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue);
14.
15. struct itimerval {
16.
17. struct timerval it_interval;
18.
19. struct timerval it_value;
20.
21. };
22.
23.
24.
25. struct timeval {
26.
27. long tv_sec;
28.
29. long tv_usec;
30.
31. }
32.
33.Release : 11/25/2006
34.
35.*/
36.
37.#include <stdio.h> // for printf()
38.
39.#include <unistd.h> // for pause()
40.
41.#include <signal.h> // for signal()
42.
43.#include <string.h> // for memset()
44.
45.#include <sys/time.h> // struct itimeral. setitimer()
46.
47.
48.
49.void printMsg(int);
50.
51.
52.
53.int main() {
54.
55. // Get system call result to determine successful or failed
56.
57. int res = 0;
58.
59. // Register printMsg to SIGALRM
60.
61. signal(SIGALRM, printMsg);
62.
63.
64.
65. struct itimerval tick;
66.
67. // Initialize struct
68.
69. memset(&tick, 0, sizeof(tick));
70.
71. // Timeout to run function first time
72.
73. tick.it_value.tv_sec = 1; // sec
74.
75. tick.it_value.tv_usec = 0; // micro sec.
76.
77. // Interval time to run function
78.
79. tick.it_interval.tv_sec = 1;
80.
81. tick.it_interval.tv_usec = 0;
82.
83. // Set timer, ITIMER_REAL : real-time to decrease timer,
84.
85. // send SIGALRM when timeout
86.
87. res = setitimer(ITIMER_REAL, &tick, NULL);
88.
89. if (res) {
90.
91. printf("Set timer failed!!/n");
92.
93. }
94.
95.
96.
97. // Always sleep to catch SIGALRM signal
98.
99. while(1) {
100.
101. pause();
102.
103. }
104.
105.
106.
107. return 0;
108.
109.}
110.
111.
112.
113.void printMsg(int num) {
114.
115. printf("%s","Hello World!!/n");
116.
117.}
当setitimer()所执行的timer时间到了,会呼叫SIGALRM signal,所以在第30行用signal()将要执行的function指定给SIGALRM。 在第43行呼叫setitimer()设定timer,但setitimer()第二个参数是sturct,负责设定timeout时间,所以第36行到第 40行设定此struct。itimerval.it_value设定第一次执行function所延迟的秒数, itimerval.it_interval设定以后每几秒执行function,所以若只想延迟一段时间执行function,只要设定 itimerval.it_value即可,若要设定间格一段时间就执行function,则it_value和it_interval都要设定,否则 funtion的第一次无法执行,就别说以后的间隔执行了。 第36行和第39行的tv_sec为sec,第37行和40行为micro sec(0.001 sec)。 第43行的第一个参数ITIMER_REAL,表示以real-time方式减少timer,在timeout时会送出SIGALRM signal。第三个参数会存放旧的timeout值,如果不需要的话,指定NULL即可。 第47 行的pause(),命令系统进入sleep状态,等待任何signal,一定要用while(1)无穷循环执行pause(),如此才能一直接收 SIGALRM signal以间隔执行function,若拿掉while(1),则function只会执行一次而已。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/fanwenbo/archive/2008/07/13/2645362.aspx