summaryrefslogtreecommitdiffstats
path: root/timer.c
blob: f634af505f4bd43a6fad534e7d989b8025c286af (plain)
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <signal.h>
#include <stdlib.h>
#include <unistd.h>

#include "include/log.h"
#include "include/list.h"
#include "include/timer.h"
#include "include/ucix.h"

/* when using this file, alarm() is used */

static struct list_head timers;

struct timer {
	struct list_head list;
	int count;
	int timeout;
	timercb_t timercb;
};

void timer_add(timercb_t timercb, int timeout)
{
	struct timer *timer;
	timer = malloc(sizeof(struct timer));
	if(!timer)
	{
		log_printf("unable to get timer buffer\n");
		return;
	}
	timer->count = 0;
	timer->timeout = timeout;
	timer->timercb = timercb;
	INIT_LIST_HEAD(&timer->list);
	list_add(&timer->list, &timers);
}

static void timer_proc(int signo)
{
	struct list_head *p;
	list_for_each(p, &timers)
	{
		struct timer *q = container_of(p, struct timer, list);
		q->count++;
		if(!(q->count%q->timeout))
		{
			q->timercb();
		}
	}
	alarm(1);
}

void timer_init(void)
{
	struct sigaction s;
	INIT_LIST_HEAD(&timers);
	s.sa_handler = timer_proc;
	s.sa_flags = 0;
	sigaction(SIGALRM, &s, NULL);
	alarm(1);
}