aboutsummaryrefslogtreecommitdiff
path: root/eventloop.c
diff options
context:
space:
mode:
Diffstat (limited to 'eventloop.c')
-rw-r--r--eventloop.c39
1 files changed, 39 insertions, 0 deletions
diff --git a/eventloop.c b/eventloop.c
new file mode 100644
index 0000000..f79114d
--- /dev/null
+++ b/eventloop.c
@@ -0,0 +1,39 @@
+#include <stdlib.h>
+#include <sys/epoll.h>
+#include "eventloop.h"
+
+struct eventLoop *eventLoopNew()
+{
+ int epollfd = epoll_create1(0);
+ if (epollfd == -1)
+ return NULL;
+
+ struct eventLoop *eventLoop = malloc(sizeof(*eventLoop));
+ eventLoop->epollfd = epollfd;
+ eventLoop->size = EVENT_LOOP_MAX_EVENTS;
+
+ return eventLoop;
+}
+
+int eventLoopAddSocket(struct eventLoop *el, struct tsocket *sock, int flag)
+{
+ struct epoll_event ev;
+ ev.events = flag;
+ ev.data.fd = sock->fd;
+
+ // TODO: How the fd ranges? Will it be larger than the MAX_EVENTS?
+ el->socks[sock->fd] = sock;
+
+ return epoll_ctl(el->epollfd, EPOLL_CTL_ADD, sock->fd, &ev);
+}
+
+int eventLoopWait(struct eventLoop *el, int timeout)
+{
+ return epoll_wait(el->epollfd, el->events, el->size, timeout);
+}
+
+struct tsocket *eventLoopGetSocket(struct eventLoop *el, int index)
+{
+ int fd = el->events[index].data.fd;
+ return el->socks[fd];
+}