Skip to content

how is the listening goroutine supposed to exit in the example? #229

@nhooyr

Description

@nhooyr

https://godoc.org/github.com/fsnotify/fsnotify#example-NewWatcher

watcher, err := fsnotify.NewWatcher()
if err != nil {
    log.Fatal(err)
}
defer watcher.Close()

done := make(chan bool)
go func() {
    for {
        select {
        case event := <-watcher.Events:
            log.Println("event:", event)
            if event.Op&fsnotify.Write == fsnotify.Write {
                log.Println("modified file:", event.Name)
            }
        case err := <-watcher.Errors:
            log.Println("error:", err)
        }
    }
}()

err = watcher.Add("/tmp/foo")
if err != nil {
    log.Fatal(err)
}
<-done

If say the watcher closes, the listening goroutine would not close, it would just remain open forever printing zero valued errors/events.

What is the correct way to use the API to ensure the goroutine exits when the watcher is closed?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions