Skip to content

Instantly share code, notes, and snippets.

@agorman
Created August 15, 2016 23:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agorman/000e5aca46827057accc8312bf55d989 to your computer and use it in GitHub Desktop.
Save agorman/000e5aca46827057accc8312bf55d989 to your computer and use it in GitHub Desktop.
inotify failing to watch a directory
package main
import (
"fmt"
"os"
"time"
"golang.org/x/exp/inotify"
)
func main() {
watcher, err := inotify.NewWatcher()
if err != nil {
panic(err)
}
watchdir := "/tmp/watchtest"
err = os.Mkdir(watchdir, 0644)
if err != nil {
if err != os.ErrExist {
panic(err)
}
}
defer os.RemoveAll(watchdir)
err = watcher.AddWatch(watchdir, inotify.IN_CREATE+inotify.IN_DELETE+inotify.IN_ISDIR)
if err != nil {
panic(err)
}
go func() {
for {
select {
case ev := <-watcher.Event:
switch ev.Mask {
case inotify.IN_CREATE + inotify.IN_ISDIR:
fmt.Println("DIR CREATED: " + ev.Name)
watcher.AddWatch(ev.Name, inotify.IN_DELETE+inotify.IN_CREATE+inotify.IN_ISDIR)
case inotify.IN_DELETE + inotify.IN_ISDIR:
fmt.Println("DIR DELETED: " + ev.Name)
watcher.RemoveWatch(ev.Name)
}
case err := <-watcher.Error:
fmt.Println("error:", err)
}
}
}()
for i := 0; i < 5; i++ {
err = os.Mkdir(watchdir+"/test", 0644)
if err != nil {
panic(err)
}
time.Sleep(time.Millisecond * 1)
err = os.Mkdir(watchdir+"/test/1", 0644)
if err != nil {
panic(err)
}
time.Sleep(time.Millisecond * 1)
err = os.RemoveAll(watchdir + "/test")
if err != nil {
panic(err)
}
time.Sleep(time.Millisecond * 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment