aboutsummaryrefslogtreecommitdiff
path: root/eventloop.c
blob: f79114da3aebab520b1e2e2edfb65789e560a523 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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];
}