document the new binlog stats
[beanstalkd.git] / sock-linux.c
blobc18eac1cd25396f18bf9dca4387eb8fa28770651
1 #include <stdlib.h>
2 #include <errno.h>
3 #include <sys/epoll.h>
4 #include "dat.h"
6 static void handle(Socket *s, int events);
8 static Handle tick;
9 static void *tickval;
10 static int epfd;
11 static int ival; // ms
14 void
15 sockinit(Handle f, void *x, int64 ns)
17 tick = f;
18 tickval = x;
19 ival = ns / 1000000;
20 epfd = epoll_create1(0);
21 if (epfd == -1) {
22 twarn("epoll_create");
23 exit(1);
28 int
29 sockwant(Socket *s, int rw)
31 int op;
32 struct epoll_event ev = {};
34 if (!s->added && !rw) {
35 return 0;
36 } else if (!s->added && rw) {
37 s->added = 1;
38 op = EPOLL_CTL_ADD;
39 } else if (!rw) {
40 op = EPOLL_CTL_DEL;
41 } else {
42 op = EPOLL_CTL_MOD;
45 switch (rw) {
46 case 'r':
47 ev.events = EPOLLIN;
48 break;
49 case 'w':
50 ev.events = EPOLLOUT;
51 break;
53 ev.events |= EPOLLRDHUP | EPOLLPRI;
54 ev.data.ptr = s;
56 return epoll_ctl(epfd, op, s->fd, &ev);
60 void
61 sockmain()
63 int i, r, n = 500;
64 int64 e, t = nanoseconds();
65 struct epoll_event evs[n];
67 for (;;) {
68 r = epoll_wait(epfd, evs, n, ival);
69 if (r == -1 && errno != EINTR) {
70 twarn("epoll_wait");
71 exit(1);
74 // should tick?
75 e = nanoseconds();
76 if ((e-t) / 1000000 > ival) {
77 tick(tickval, 0);
78 t = e;
81 for (i=0; i<r; i++) {
82 handle(evs[i].data.ptr, evs[i].events);
89 static void
90 handle(Socket *s, int evset)
92 int c = 0;
94 if (evset & EPOLLIN) {
95 c = 'r';
96 } else if (evset & EPOLLOUT) {
97 c = 'w';
100 s->f(s->x, c);