Last active
December 30, 2020 20:31
-
-
Save ast/c410d90a814aa5af879974f312bbafe3 to your computer and use it in GitHub Desktop.
Using epoll with go. Packages like fsnotify does not work with sysfs. Then you need epoll, poll or select.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"golang.org/x/sys/unix" | |
"log" | |
"os" | |
) | |
func main() { | |
file, err := os.Open("/sys/class/somefile") | |
if err != nil { | |
log.Fatal(err) | |
} | |
epfd, err := unix.EpollCreate(5) // 5 is just an example, see man page. | |
if err != nil { | |
log.Fatal(err) | |
} | |
events := make([]unix.EpollEvent, 1, 5) | |
events[0] = unix.EpollEvent{ | |
Events: unix.EPOLLPRI | unix.EPOLLHUP | unix.EPOLLERR, | |
Fd: int32(file.Fd()), | |
} | |
err = unix.EpollCtl(epfd, unix.EPOLL_CTL_ADD, int(file.Fd()), &events[0]) | |
if err != nil { | |
log.Fatal(err) | |
} | |
bs := make([]byte, 100, 100) | |
for { | |
n, err := unix.EpollWait(epfd, events, -1) | |
if err != nil { | |
log.Fatal(err) | |
} | |
r, err := file.Read(bs) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// seek to beginning to relatch event | |
file.Seek(0, 0) | |
log.Printf("%v %v %v", n, r, string(bs[0:r])) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment