mirror of
https://github.com/DominicBreuker/pspy.git
synced 2025-12-21 03:34:50 +00:00
integrate inotify syscalls
This commit is contained in:
65
internal/inotify/inotify.go
Normal file
65
internal/inotify/inotify.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package inotify
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
type Inotify struct {
|
||||
fd int
|
||||
watchers []*watcher
|
||||
ping chan struct{}
|
||||
paused bool
|
||||
}
|
||||
|
||||
func NewInotify(ping chan struct{}) (*Inotify, error) {
|
||||
fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC)
|
||||
if fd == -1 {
|
||||
return nil, fmt.Errorf("Can't init inotify: %d", errno)
|
||||
}
|
||||
|
||||
i := &Inotify{
|
||||
fd: fd,
|
||||
ping: ping,
|
||||
paused: false,
|
||||
}
|
||||
go watch(i)
|
||||
|
||||
return i, nil
|
||||
}
|
||||
|
||||
func (i *Inotify) Watch(dir string) error {
|
||||
w, err := newWatcher(i.fd, dir, i.ping)
|
||||
if err != nil {
|
||||
return fmt.Errorf("creating watcher: %v", err)
|
||||
}
|
||||
i.watchers = append(i.watchers, w)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (i *Inotify) Pause() {
|
||||
i.paused = true
|
||||
}
|
||||
|
||||
func (i *Inotify) UnPause() {
|
||||
i.paused = false
|
||||
}
|
||||
|
||||
func (i *Inotify) String() string {
|
||||
dirs := make([]string, 0)
|
||||
for _, w := range i.watchers {
|
||||
dirs = append(dirs, w.dir)
|
||||
}
|
||||
return fmt.Sprintf("Watching: %v", dirs)
|
||||
}
|
||||
|
||||
func watch(i *Inotify) {
|
||||
buf := make([]byte, 1024)
|
||||
for {
|
||||
_, _ = unix.Read(i.fd, buf)
|
||||
if !i.paused {
|
||||
i.ping <- struct{}{}
|
||||
}
|
||||
}
|
||||
}
|
||||
25
internal/inotify/watcher.go
Normal file
25
internal/inotify/watcher.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package inotify
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
const events = unix.IN_ALL_EVENTS
|
||||
|
||||
type watcher struct {
|
||||
wd int
|
||||
dir string
|
||||
}
|
||||
|
||||
func newWatcher(fd int, dir string, ping chan struct{}) (*watcher, error) {
|
||||
wd, errno := unix.InotifyAddWatch(fd, dir, events)
|
||||
if wd == -1 {
|
||||
return nil, fmt.Errorf("adding watcher on %s: %d", dir, errno)
|
||||
}
|
||||
return &watcher{
|
||||
wd: wd,
|
||||
dir: dir,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user