From 7369505397cdfddf0883e2c24e1652df8bd488fe Mon Sep 17 00:00:00 2001 From: Guangxiong Lin Date: Fri, 16 Dec 2022 13:53:35 +0800 Subject: Refactor file structure --- src/evloop.c | 89 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 src/evloop.c (limited to 'src/evloop.c') diff --git a/src/evloop.c b/src/evloop.c new file mode 100644 index 0000000..5bed1e9 --- /dev/null +++ b/src/evloop.c @@ -0,0 +1,89 @@ +#include +#include + +#include "evloop.h" +#include "util.h" +#include "constant.h" +#include "tpool.h" + +struct evloop { + int epollfd; + struct epoll_event events[EVENT_LOOP_MAX_EVENTS]; + int size; +}; + +evloop_t *evloop_create() +{ + int epollfd = epoll_create1(0); + if (epollfd == -1) + return NULL; + + evloop_t *eventLoop = malloc(sizeof(*eventLoop)); + eventLoop->epollfd = epollfd; + eventLoop->size = EVENT_LOOP_MAX_EVENTS; + + return eventLoop; +} + +int evloop_wait(evloop_t *el, int timeout) +{ + return epoll_wait(el->epollfd, el->events, el->size, timeout); +} + +int evloop_add(evloop_t *el, event_t *ev, int flag) +{ + struct epoll_event epev; + epev.events = flag; + epev.data.ptr = ev; + + return epoll_ctl(el->epollfd, EPOLL_CTL_ADD, ev->fd, &epev); +} + +event_t *evloop_get(evloop_t *el, int index) +{ + return (event_t *)el->events[index].data.ptr; +} + +void evloop_loop(evloop_t *el) +{ + int nevents; + event_t *ev; + + for (;;) { + nevents = evloop_wait(el, -1); + if (nevents == -1) + panic("eventloop wait"); + + for (int i = 0; i < nevents; i++) { + ev = evloop_get(el, i); + // TODO: detect if there is any issue of the handle function + // and delete the event when issues happen + tpool_add_work(tpool, ev->process, ev->data); + } + } +} + +int evloop_remove(evloop_t *el, event_t *ev) +{ + if (epoll_ctl(el->epollfd, EPOLL_CTL_DEL, ev->fd, NULL) == -1) + return ERROR; + + if (ev->destroy) + ev->destroy(ev->data); + free(ev); + + return OK; +} + +event_t *event_create(void *data, int fd, + evloop_process_func_t process, + evloop_destroy_func_t destroy) +{ + event_t *ev = malloc(sizeof(*ev)); + ev->data = data; + ev->process = process; + ev->fd = fd; + ev->destroy = destroy; + + return ev; +} -- cgit v1.2.3