forked from beanstalkd/beanstalkd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linux.c
86 lines (72 loc) · 1.46 KB
/
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
#define _XOPEN_SOURCE 600
#include "dat.h"
#include <unistd.h>
#include <sys/types.h>
#include <stdint.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/epoll.h>
#ifndef EPOLLRDHUP
#define EPOLLRDHUP 0x2000
#endif
static int epfd;
int
sockinit(void)
{
epfd = epoll_create(1);
if (epfd == -1) {
twarn("epoll_create");
return -1;
}
return 0;
}
int
sockwant(Socket *s, int rw)
{
int op;
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;
}
struct epoll_event ev = {.events=0};
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);
}
int
socknext(Socket **s, int64 timeout)
{
int r;
struct epoll_event ev = {.events=0};
r = epoll_wait(epfd, &ev, 1, (int)(timeout/1000000));
if (r == -1 && errno != EINTR) {
twarn("epoll_wait");
exit(1);
}
if (r > 0) {
*s = ev.data.ptr;
if (ev.events & (EPOLLHUP|EPOLLRDHUP)) {
return 'h';
} else if (ev.events & EPOLLIN) {
return 'r';
} else if (ev.events & EPOLLOUT) {
return 'w';
}
}
return 0;
}