-
Notifications
You must be signed in to change notification settings - Fork 9
/
mux-kqueue.c
145 lines (115 loc) · 2.26 KB
/
mux-kqueue.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include "mux.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/event.h>
struct mux {
int fd;
};
int
mux_open(loop_t *loop, int event_max)
{
loop->mux = malloc(sizeof(struct mux));
if (loop->mux == NULL) {
goto err;
}
loop->mux->fd = kqueue();
if (loop->mux->fd == -1) {
goto err;
}
return LOOP_OK;
err:
free(loop->mux);
return LOOP_ERROR;
}
void
mux_close(loop_t *loop)
{
free(loop->mux);
}
int
mux_set_event(loop_t *loop, int fd, int tag, int type)
{
struct kevent event;
if (type & LOOP_WRITE) {
EV_SET(&event, fd, EVFILT_WRITE, EV_ADD, 0, 0, NULL);
}
if (type & LOOP_READ) {
EV_SET(&event, fd, EVFILT_READ, EV_ADD, 0, 0, NULL);
}
if (kevent(loop->mux->fd, &event, 1, NULL, 0, NULL) == -1) {
return LOOP_ERR;
}
return LOOP_OK;
}
int
mux_del_event(loop_t *loop, int fd, int type)
{
struct kevent event;
if (type & LOOP_WRITE) {
EV_SET(&event, fd, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
}
if (type & LOOP_READ) {
EV_SET(&event, fd, EVFILT_READ, EV_DELETE, 0, 0, NULL);
}
if (kevent(loop->mux->fd, &event, 1, NULL, 0, NULL) == -1) {
return LOOP_ERR;
}
return LOOP_OK;
}
#define EVENTS_NR 128
int
mux_polling(loop_t *loop, void *timer)
{
int i;
int n;
int fd;
struct timespec *timeout;
struct timespec timespec;
struct kevent events[EVENTS_NR];
if (timer == NULL) {
timeout = NULL;
} else {
timespec.tv_sec = ((timer_t *)timer)->seconds;
timespec.tv_nsec = ((timer_t *)timer)->nanoseconds;
timeout = ×pec;
}
n = kevent(loop->mux->fd, NULL, 0, events, EVENTS_NR, timeout);
if (n == -1) {
if (errno == EINTR) {
n = 0;
} else {
return LOOP_ERR;
}
}
loop_timer_dispatch(loop);
for (i = 0; i < n; i++) {
int type;
struct event *event;
loop_proc_t *proc;
fd = events[i].ident;
event = &loop->event[fd];
if ((proc = event->proc) == NULL) {
continue;
}
type = 0;
if (events[i].flags & EV_EOF) {
type = LOOP_EOF;
} else {
switch (events[i].filter) {
case EVFILT_READ:
type = LOOP_READ;
break;
case EVFILT_WRITE:
type = LOOP_WRITE;
break;
default:
continue;
}
}
proc(loop, fd, event->tag, type, event->flag, event->args);
}
return LOOP_OK;
}