I use the library (http://github.com/fsnotify/fsnotify) to monitor the file system.

I m trying to adjust the repository example to match my requirements, but when i do so the program is not working anymore.

I commented the done channel within the ExampleNewWatcher function

done := make(chan bool)
<-done

As a result, now when i run the example, this channel does not output anything anymore.

event, ok := <-watcher.Events

Complete codeļ¼š

package main

import (
    "github.com/fsnotify/fsnotify"
    "log"
    "os"
    "strconv"
    "time"
)

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

    done := make(chan bool) // if i commen this line the `panic` not norking
    go func() {
        for {
            select {
            case event, ok := <-watcher.Events:
                if !ok {
                    return
                }
                log.Println("event:", event)
                if event.Op&fsnotify.Write == fsnotify.Write {
                    log.Println("modified file:", event.Name)
                }
                panic("just for test") // new output this line

            case err, ok := <-watcher.Errors:
                if !ok {
                    return
                }
                log.Println("error:", err)
            }
        }
    }()

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

func check(err error) {
    if err != nil {
        panic(err)
    }

}
func main() {
    // create the test file
    var err error
    file, err := os.Create("/tmp/foo")
    check(err)

    _, err = file.Write([]byte("hello world"))
    check(err)

    stopchan := make(chan struct{})

    // test change file
    go func() {

        for i := 0; i < 10; i++ {
            file1, err := os.OpenFile("/tmp/foo", os.O_RDWR, 0644)
            check(err)
            d := strconv.Itoa(i) + "hello world"
            _, err = file1.Write([]byte(d))
            check(err)
            err = file1.Close()
            check(err)
            time.Sleep(2 * time.Second) // wait the context  writed to the file
        }

    }()

    ExampleNewWatcher() // monitor file

    stopchan <- struct{}{}
}

0 Answers