-
Notifications
You must be signed in to change notification settings - Fork 0
/
fibre_io.c
60 lines (54 loc) · 1.09 KB
/
fibre_io.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
#include <unistd.h>
#include <sys/epoll.h>
#include <sys/socket.h>
#include <sys/timerfd.h>
#include "fibre.h"
#include "fibre_io.h"
ssize_t fibre_write(int fd, const char *buf, unsigned long n)
{
struct epoll_event ev = { 0 };
ev.data.fd = fd;
ev.events = EPOLLOUT;
fibre_yield(&ev);
return write(fd, buf, n);
}
ssize_t fibre_read(int fd, char *buf, unsigned long n)
{
struct epoll_event ev = { 0 };
ev.data.fd = fd;
ev.events = EPOLLIN;
fibre_yield(&ev);
return read(fd, buf, n);
}
int fibre_accept(int fd)
{
struct epoll_event ev = { 0 };
ev.data.fd = fd;
ev.events = EPOLLIN;
fibre_yield(&ev);
return accept(fd, 0, 0);
}
int fibre_sleep(long ms)
{
int status = 0;
int fd = timerfd_create(CLOCK_MONOTONIC, 0);
if (fd < 0) {
status = -1;
goto failed;
}
struct itimerspec t = { 0 };
t.it_value.tv_sec = ms / 1000;
t.it_value.tv_nsec = 1000 * 1000 * (ms % 1000);
if (timerfd_settime(fd, 0, &t, 0) < 0) {
status = -1;
goto cleanup_fd;
}
struct epoll_event ev = { 0 };
ev.data.fd = fd;
ev.events = EPOLLIN;
fibre_yield(&ev);
cleanup_fd:
close(fd);
failed:
return status;
}