#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]; }