4863
|
1 /* POSIX compatible timer callback */
|
|
2 #include <sys/time.h>
|
|
3 #include <signal.h>
|
|
4 #include <stddef.h>
|
|
5
|
|
6 #include "timer.h"
|
|
7
|
|
8 static timer_callback *user_func = NULL;
|
|
9 static struct itimerval otimer;
|
|
10 static void (*old_alrm)(int) = SIG_DFL;
|
|
11
|
|
12 static void my_alarm_handler( int signo )
|
|
13 {
|
|
14 if(user_func) (*user_func)();
|
|
15 }
|
|
16
|
|
17 unsigned set_timer_callback(unsigned ms,timer_callback func)
|
|
18 {
|
|
19 unsigned ret;
|
|
20 struct itimerval itimer;
|
|
21 user_func = func;
|
|
22 getitimer(ITIMER_REAL,&otimer);
|
|
23 old_alrm = signal(SIGALRM,my_alarm_handler);
|
|
24 signal(SIGALRM,my_alarm_handler);
|
|
25 itimer.it_interval.tv_sec = 0;
|
|
26 itimer.it_interval.tv_usec = ms*1000;
|
|
27 itimer.it_value.tv_sec = 0;
|
|
28 itimer.it_value.tv_usec = ms*1000;
|
|
29 setitimer(ITIMER_REAL,&itimer,NULL);
|
|
30 getitimer(ITIMER_REAL,&itimer);
|
|
31 ret = itimer.it_interval.tv_sec*1000 + itimer.it_interval.tv_usec/1000;
|
|
32 if(!ret) restore_timer();
|
|
33 return ret;
|
|
34 }
|
|
35
|
|
36 void restore_timer(void)
|
|
37 {
|
|
38 signal(SIGALRM,old_alrm);
|
|
39 setitimer(ITIMER_REAL,&otimer,NULL);
|
|
40 }
|