-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpoll_linux.go
100 lines (79 loc) · 2.04 KB
/
poll_linux.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
// Copyright 2019, Shulhan <[email protected]>. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
//go:build linux
// +build linux
package net
import (
"fmt"
"log"
"golang.org/x/sys/unix"
)
type epoll struct {
events [maxQueue]unix.EpollEvent
read int
}
// NewPoll create and initialize new poll using epoll for Linux system or
// kqueue for BSD or Darwin (macOS).
func NewPoll() (Poll, error) {
var err error
ep := &epoll{}
ep.read, err = unix.EpollCreate1(0)
if err != nil {
return nil, fmt.Errorf("epoll.NewPoll: %s", err.Error())
}
return ep, nil
}
func (poll *epoll) Close() {
unix.Close(poll.read)
}
func (poll *epoll) RegisterRead(fd int) (err error) {
event := unix.EpollEvent{
Events: unix.EPOLLIN | unix.EPOLLONESHOT,
Fd: int32(fd),
}
err = unix.SetNonblock(fd, true)
if err != nil {
return fmt.Errorf("epoll.RegisterRead: %s", err.Error())
}
err = unix.EpollCtl(poll.read, unix.EPOLL_CTL_ADD, fd, &event)
if err != nil {
return fmt.Errorf("epoll.RegisterRead: %s", err.Error())
}
return nil
}
func (poll *epoll) ReregisterRead(idx, fd int) {
poll.events[idx].Events = unix.EPOLLIN | unix.EPOLLONESHOT
err := unix.EpollCtl(poll.read, unix.EPOLL_CTL_MOD, fd, &poll.events[idx])
if err != nil {
log.Println("epoll.RegisterRead: unix.EpollCtl: " + err.Error())
err = poll.UnregisterRead(fd)
if err != nil {
log.Println("epoll.RegisterRead: " + err.Error())
}
}
}
func (poll *epoll) UnregisterRead(fd int) (err error) {
err = unix.EpollCtl(poll.read, unix.EPOLL_CTL_DEL, fd, nil)
if err != nil {
return fmt.Errorf("epoll.UnregisterRead: %s", err.Error())
}
return nil
}
func (poll *epoll) WaitRead() (fds []int, err error) {
var n int
for {
n, err = unix.EpollWait(poll.read, poll.events[:], -1)
if err != nil {
if err == unix.EINTR {
continue
}
return nil, fmt.Errorf("epoll.WaitRead: %s", err.Error())
}
break
}
for x := 0; x < n; x++ {
fds = append(fds, int(poll.events[x].Fd))
}
return fds, nil
}