Created
August 15, 2016 23:15
-
-
Save agorman/000e5aca46827057accc8312bf55d989 to your computer and use it in GitHub Desktop.
inotify failing to watch a directory
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 ( | |
"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