From 14eb75c7f5e90f3c1174cdf700753d74bbd358a8 Mon Sep 17 00:00:00 2001 From: Guangxiong Lin Date: Fri, 2 Dec 2022 01:04:51 +0800 Subject: Abstract accept and handle as event --- eventloop.c | 57 ++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 9 deletions(-) (limited to 'eventloop.c') diff --git a/eventloop.c b/eventloop.c index 9a26b98..970a521 100644 --- a/eventloop.c +++ b/eventloop.c @@ -1,6 +1,8 @@ #include #include + #include "eventloop.h" +#include "util.h" struct eventLoop *eventLoopNew() { @@ -15,15 +17,6 @@ struct eventLoop *eventLoopNew() return eventLoop; } -int eventLoopAddSocket(struct eventLoop *el, struct tsocket *sock, int flag) -{ - struct epoll_event ev; - ev.events = flag; - ev.data.ptr = 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); @@ -33,3 +26,49 @@ struct tsocket *eventLoopGetSocket(struct eventLoop *el, int index) { return (struct tsocket *)el->events[index].data.ptr; } + +int eventLoopAdd(struct eventLoop *el, struct event *ev, int flag) +{ + struct epoll_event epev; + epev.events = flag; + epev.data.ptr = ev; + + ev->el = el; + + return epoll_ctl(el->epollfd, EPOLL_CTL_ADD, ev->fd, &epev); +} + +struct event *eventLoopGet(struct eventLoop *el, int index) +{ + return (struct event *)el->events[index].data.ptr; +} + +void eventLoopLoop(struct eventLoop *el) +{ + int nevents; + struct event *ev; + + for (;;) { + nevents = eventLoopWait(el, -1); + if (nevents == -1) + panic("eventloop wait"); + + for (int i = 0; i < nevents; i++) { + ev = eventLoopGet(el, i); + ev->handle(ev); + } + } +} + +int eventLoopDel(struct eventLoop *el, struct event *ev) +{ + if (epoll_ctl(el->epollfd, EPOLL_CTL_DEL, ev->fd, NULL) == -1) + return ERROR; + + if (ev->delete) + ev->delete(ev); + else + free(ev); + + return OK; +} -- cgit v1.2.3