From a9501d10847d7993fad2e0778fe9c11317b4f7be Mon Sep 17 00:00:00 2001 From: Guangxiong Lin Date: Thu, 1 Dec 2022 23:20:33 +0800 Subject: Simplify logic by structure --- eventloop.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 eventloop.c (limited to 'eventloop.c') 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 +#include +#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]; +} -- cgit v1.2.3