forked from alberliu/gn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathepoll.go
105 lines (91 loc) · 1.88 KB
/
epoll.go
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
// +build linux
package gn
import (
"golang.org/x/sys/unix"
"syscall"
)
const (
EpollListener = syscall.EPOLLIN | syscall.EPOLLPRI | syscall.EPOLLERR | syscall.EPOLLHUP | unix.EPOLLET
EpollRead = syscall.EPOLLIN | syscall.EPOLLPRI | syscall.EPOLLERR | syscall.EPOLLHUP | unix.EPOLLET
)
type epoll struct {
fd int
lfd int32
}
func EpollCreate(port int) (*epoll, error) {
lfd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0)
if err != nil {
log.Error(err)
return nil, err
}
err = syscall.Bind(lfd, &syscall.SockaddrInet4{Port: port})
if err != nil {
log.Error(err)
return nil, err
}
err = syscall.Listen(lfd, 1024)
if err != nil {
log.Error(err)
return nil, err
}
fd, err := syscall.EpollCreate1(0)
if err != nil {
log.Error(err)
return nil, err
}
err = syscall.EpollCtl(fd, syscall.EPOLL_CTL_ADD, lfd, &syscall.EpollEvent{
Events: EpollListener,
Fd: int32(lfd),
})
if err != nil {
log.Error(err)
return nil, err
}
return &epoll{
fd: fd,
lfd: int32(lfd),
}, nil
}
func (e *epoll) AddRead(fd int) error {
err := syscall.EpollCtl(e.fd, syscall.EPOLL_CTL_ADD, fd, &syscall.EpollEvent{
Events: EpollRead,
Fd: int32(fd),
})
if err != nil {
return err
}
return nil
}
func (e *epoll) RemoveAndClose(fd int) error {
// 移除文件描述符的监听
err := syscall.EpollCtl(e.fd, syscall.EPOLL_CTL_DEL, fd, nil)
if err != nil {
return err
}
err = syscall.Close(fd)
if err != nil {
return err
}
return nil
}
func (e *epoll) EpollWait(handler func(event Event)) error {
events := make([]syscall.EpollEvent, 100)
n, err := syscall.EpollWait(e.fd, events, -1)
if err != nil {
return err
}
for i := 0; i < n; i++ {
if events[i].Fd == e.lfd {
handler(Event{
Fd: events[i].Fd,
Type: EventConn,
})
} else {
handler(Event{
Fd: events[i].Fd,
Type: EventIn,
})
}
}
return nil
}