-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathepoll.c
103 lines (83 loc) · 2.29 KB
/
epoll.c
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "epoll.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "connection.h"
#include "handlers.h"
#include "log.h"
#include "panic.h"
#include "socket.h"
struct epoll* make_epoll() {
struct epoll* epoll = malloc(sizeof(struct epoll));
epoll->fd = epoll_create1(0);
if (epoll->fd < 0) {
panic_errno();
}
epoll->events = malloc(kMaxConnectionsNumber * sizeof(struct epoll_event));
if (epoll->events == NULL) {
panic_errno();
}
return epoll;
}
void handle_connection(struct epoll* epoll, int fd) {
struct connection* connection = get_connection(fd);
assert(connection->callback != NULL);
connection->callback(epoll, fd);
if (connection->state == kClosed) {
delete_connection(fd);
if (close(fd) < 0) {
panic_errno();
}
}
}
__attribute__((noreturn)) void serve_connections(struct epoll* epoll) {
for (;;) {
int number_of_ready_descriptors =
epoll_wait(epoll->fd, epoll->events, kMaxConnectionsNumber, -1);
for (int index = 0; index < number_of_ready_descriptors; ++index) {
handle_connection(epoll, epoll->events[index].data.fd);
}
}
}
void add_listener_fd(struct epoll* epoll, int fd) {
make_socket_non_blocking(fd);
struct connection* connection = make_connection(fd);
struct epoll_event event = {0};
event.data.fd = fd;
event.events = EPOLLIN;
if (epoll_ctl(epoll->fd, EPOLL_CTL_ADD, fd, &event) < 0) {
panic_errno();
}
connection->callback = &listener_callback;
}
void create_connection(struct epoll* /*epoll*/, int fd) {
if (fd > kMaxConnectionsNumber) {
close(fd);
LOG_ERROR("too much connections: %d", fd);
return;
}
make_socket_non_blocking(fd);
make_connection(fd);
}
void listen_to_read_events(struct epoll* epoll, int fd) {
struct epoll_event event = {0};
event.data.fd = fd;
event.events |= EPOLLIN;
if (epoll_ctl(epoll->fd, EPOLL_CTL_ADD, fd, &event) < 0) {
panic_errno();
}
}
void mute(struct epoll* epoll, int fd) {
if (epoll_ctl(epoll->fd, EPOLL_CTL_DEL, fd, NULL) < 0) {
panic_errno();
}
}
void listen_to_write_events(struct epoll* epoll, int fd) {
struct epoll_event event = {0};
event.data.fd = fd;
event.events |= EPOLLOUT;
if (epoll_ctl(epoll->fd, EPOLL_CTL_ADD, fd, &event) < 0) {
panic_errno();
}
}