forked from beanstalkd/beanstalkd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sock-linux.c
107 lines (87 loc) · 1.76 KB
/
sock-linux.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
104
105
106
107
#include <stdlib.h>
#include <errno.h>
#include <sys/epoll.h>
#include "dat.h"
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0x2000
#endif
static void handle(Socket *s, int events);
static Handle tick;
static void *tickval;
static int epfd;
static int ival; // ms
void
sockinit(Handle f, void *x, int64 ns)
{
tick = f;
tickval = x;
ival = ns / 1000000;
epfd = epoll_create(1);
if (epfd == -1) {
twarn("epoll_create");
exit(1);
}
}
int
sockwant(Socket *s, int rw)
{
int op;
struct epoll_event ev = {};
if (!s->added && !rw) {
return 0;
} else if (!s->added && rw) {
s->added = 1;
op = EPOLL_CTL_ADD;
} else if (!rw) {
op = EPOLL_CTL_DEL;
} else {
op = EPOLL_CTL_MOD;
}
switch (rw) {
case 'r':
ev.events = EPOLLIN;
break;
case 'w':
ev.events = EPOLLOUT;
break;
}
ev.events |= EPOLLRDHUP | EPOLLPRI;
ev.data.ptr = s;
return epoll_ctl(epfd, op, s->fd, &ev);
}
void
sockmain()
{
int i, r, n = 1;
int64 e, t = nanoseconds();
struct epoll_event evs[n];
for (;;) {
r = epoll_wait(epfd, evs, n, ival);
if (r == -1 && errno != EINTR) {
twarn("epoll_wait");
exit(1);
}
// should tick?
e = nanoseconds();
if ((e-t) / 1000000 > ival) {
tick(tickval, 0);
t = e;
}
for (i=0; i<r; i++) {
handle(evs[i].data.ptr, evs[i].events);
}
}
}
static void
handle(Socket *s, int evset)
{
int c = 0;
if (evset & (EPOLLHUP|EPOLLRDHUP)) {
c = 'h';
} else if (evset & EPOLLIN) {
c = 'r';
} else if (evset & EPOLLOUT) {
c = 'w';
}
s->f(s->x, c);
}