FSNotify在运行时添加监视目录

huangapple go评论91阅读模式
英文:

FSNotify add watch directories while running

问题

我不太知道如何表达问题,但是这是问题的内容。

我正在使用fsnotify来监视一些目录的变化,当文件发生变化时,我会将变化同步到另一个目录。但是我想要将新创建的目录也添加到监视中,但这并没有起作用。

这是我的代码:

func Watcher() {
    watcher, err := fsnotify.NewWatcher()
    defer watcher.Close()

    done := make(chan bool)
    go func() {
        for {
            select {
            case event := <-watcher.Events:
                if file.Mode().IsDir() {
                    err = os.Mkdir(dest, 0755)
                    err = watcher.Add(dest)
                }
            case err := <-watcher.Errors:
                log.Println("error:", err)
            }
        }
    }()

    dirs, err := readLines("dirs")
    for _, el := range dirs {
        err = watcher.Add(el)
    }
    check(err)
    <-done
}

这个函数还有更长的部分,但我删除了不重要的部分。除了err = watcher.Add(dest)之外,其他都正常工作。

我该如何使其监视更多的目录?

英文:

I don't really know how to formulate the question, but here it is.

I'm using fsnotify to watch some directories for changes and when a file changes, I sync the change to another directory. But I want to add newly created directories to the watch too and it's not really working.

Here's my code:

func Watcher() {
    watcher, err := fsnotify.NewWatcher()
    defer watcher.Close()

    done := make(chan bool)
    go func() {
        for {
            select {
            case event := &lt;-watcher.Events:
             
                    if file.Mode().IsDir() {
                    err = os.Mkdir(dest, 0755)
                    err = watcher.Add(dest)

            }
        case err := &lt;-watcher.Errors:
            log.Println(&quot;error:&quot;, err)
        }
    }
    }()

    dirs, err := readLines(&quot;dirs&quot;)
    for _, el := range dirs {
        err = watcher.Add(el)
    }
    check(err)
    &lt;-done
}

The function is much longer, but I've deleted the non-important parts. Everything works, except the err = watcher.Add(dest).

How can I make it watch more directories?

答案1

得分: 0

这是要翻译的内容:

"它之前运行得很好,但是我弄错了一些变量。应该是watcher.Add(event.Name)而不是watcher.Add(dest)。"

英文:

It was working just fine, but I got some variables wrong. Should have been watcher.Add(event.Name) instead of watcher.Add(dest).

huangapple
  • 本文由 发表于 2017年3月27日 09:41:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/43036659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定