]> Dogcows Code - chaz/tint2/blob - src/util/timer.c
*fix* make timer non-blocking to fix freezing when a timer is resetted in a callback...
[chaz/tint2] / src / util / timer.c
1 /**************************************************************************
2 *
3 * Copyright (C) 2009 Andreas.Fink (Andreas.Fink85@gmail.com)
4 *
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License version 2
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program; if not, write to the Free Software
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 **************************************************************************/
17
18 #include <sys/timerfd.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21 #include <fcntl.h>
22
23 #include "timer.h"
24
25 GSList* timer_list = 0;
26
27 int install_timer(int value_sec, int value_nsec, int interval_sec, int interval_nsec, void (*_callback)())
28 {
29 if ( value_sec < 0 || interval_sec < 0 || _callback == 0 )
30 return -1;
31
32 int timer_fd;
33 struct itimerspec timer;
34 timer.it_value = (struct timespec){ .tv_sec=value_sec, .tv_nsec=value_nsec };
35 timer.it_interval = (struct timespec){ .tv_sec=interval_sec, .tv_nsec=interval_nsec };
36 timer_fd = timerfd_create(CLOCK_MONOTONIC, 0);
37 timerfd_settime(timer_fd, 0, &timer, 0);
38 struct timer* t = malloc(sizeof(struct timer));
39 t->id=timer_fd;
40 t->_callback = _callback;
41 timer_list = g_slist_prepend(timer_list, t);
42
43 int flags = fcntl( timer_fd, F_GETFL, 0 );
44 if( flags != -1 )
45 fcntl( timer_fd, F_SETFL, flags | O_NONBLOCK );
46
47 return timer_fd;
48 }
49
50
51 void reset_timer(int id, int value_sec, int value_nsec, int interval_sec, int interval_nsec)
52 {
53 struct itimerspec timer;
54 timer.it_value = (struct timespec){ .tv_sec=value_sec, .tv_nsec=value_nsec };
55 timer.it_interval = (struct timespec){ .tv_sec=interval_sec, .tv_nsec=interval_nsec };
56 timerfd_settime(id, 0, &timer, 0);
57 }
58
59
60 void uninstall_timer(int id)
61 {
62 close(id);
63 GSList* timer_iter = timer_list;
64 while (timer_iter) {
65 struct timer* t = timer_iter->data;
66 if (t->id == id) {
67 timer_list = g_slist_remove(timer_list, t);
68 free(t);
69 return;
70 }
71 timer_iter = timer_iter->next;
72 }
73 }
This page took 0.038948 seconds and 5 git commands to generate.