Created
March 19, 2021 15:27
-
-
Save z0marlin/b68bf83c15378afff585f7104ae7456e to your computer and use it in GitHub Desktop.
Sample go code to monitor changes to mounts on linux using epoll
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 ( | |
"log" | |
"os" | |
"syscall" | |
) | |
const mpath = "/proc/mounts" | |
func main() { | |
epfd, err := syscall.EpollCreate(1) | |
if err != nil { | |
log.Fatalf("Failed to create epoll: %v", err) | |
} | |
f, err := os.Open(mpath) | |
if err != nil { | |
log.Fatalf("Failed to open mounts file: %v", err) | |
} | |
err = syscall.EpollCtl(epfd, syscall.EPOLL_CTL_ADD, int(f.Fd()), &syscall.EpollEvent{ | |
// Events generated when the mounts are changed are EPOLLPRI and EPOLLERR. | |
// Read http://lkml.iu.edu/hypermail/linux/kernel/1012.1/02246.html | |
Events: syscall.EPOLLPRI | syscall.EPOLLERR, | |
Fd: int32(f.Fd()), | |
}) | |
if err != nil { | |
log.Fatalf("Failed to update epoll interest list: %v", err) | |
} | |
events := make([]syscall.EpollEvent, 2) | |
for true { | |
log.Println("Waiting for events...") | |
// Wait for events on the mounts file indefinitely | |
n, err := syscall.EpollWait(epfd, events, -1) | |
if err != nil { | |
log.Fatalf("Erro while waiting for events: %v", err) | |
} | |
processEvents(events, n) | |
} | |
} | |
func processEvents(events []syscall.EpollEvent, count int) { | |
log.Printf("Processing %d events...\n", count) | |
for i := 0; i < count; i++ { | |
log.Println(events[i]) | |
ev := events[i].Events | |
if (ev & syscall.EPOLLPRI) > 0 { | |
log.Println("EPOLLPRI ") | |
} | |
if (ev & syscall.EPOLLIN) > 0 { | |
log.Println("EPOLLIN ") | |
} | |
if (ev & syscall.EPOLLERR) > 0 { | |
log.Println("EPOLLERR ") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment