aboutsummaryrefslogtreecommitdiffstats
path: root/package/libtapi/src/events.c
blob: 36e9b62a01271550efabdf7021c3e29c329e912f (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
#include <stdbool.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <errno.h>

#include <stdio.h>

#include "events.h"

struct event_callback *event_callbacks;

static int event_epoll_fd = -1;

int event_register(int fd, int events, struct event_callback *cb)
{
	struct epoll_event ev;

	if (event_epoll_fd == -1)
		event_epoll_fd = epoll_create(1);

	ev.events = events;
	ev.data.ptr = cb;

	cb->fd = fd;

	return epoll_ctl(event_epoll_fd, EPOLL_CTL_ADD, fd, &ev);
}

int	event_unregister(int fd)
{
	return epoll_ctl(event_epoll_fd, EPOLL_CTL_DEL, fd, NULL);
}

int tapi_mainloop(void)
{
	struct epoll_event ev[10];
	struct event_callback *cb;
	int ret;
	bool keep;
	int i;

	if (event_epoll_fd == -1)
		event_epoll_fd = epoll_create(1);

	while(true) {
		ret = epoll_wait(event_epoll_fd, ev, 10, -1);
		for(i = 0; i < ret; ++i) {
			cb = ev[i].data.ptr;
			keep = cb->callback(ev[i].events, cb->data);
			if (!keep)
				event_unregister(cb->fd);
		}
		if (ret < 0)
			printf("epoll: %d\n", errno);
	}

	return 0;
}