去语言如何检测文件更改?

ang*_*ius 26 go

我需要知道如何使用Go检测文件何时更改.我知道Unix提供了一个名为的函数fcntl(),它通知特定文件何时被更改,但我没有在Go中找到这个.请帮我.

kos*_*tix 13

我想补充一下peterSO的答案,如果你实际上想要通过其他一些进程读取附加到文件的数据 - tail在Unix中做什么程序,那么最好让tail自己做好自己的工作.监视文件并消耗它输出的内容.这可以通过tail使用exec包中的StdoutPipe函数运行来实现.

tail在我看来,使用这种任务是比较好的,因为tail已经教会使用一堆聪明的技巧,包括检测文件替换(通常在监视通过logrotate或类似的东西旋转的日志文件时发生).


lau*_*ent 12

这是一个简单的跨平台版本:

func watchFile(filePath string) error {
    initialStat, err := os.Stat(filePath)
    if err != nil {
        return err
    }

    for {
        stat, err := os.Stat(filePath)
        if err != nil {
            return err
        }

        if stat.Size() != initialStat.Size() || stat.ModTime() != initialStat.ModTime() {
            break
        }

        time.Sleep(1 * time.Second)
    }

    return nil
}
Run Code Online (Sandbox Code Playgroud)

使用方式如下:

doneChan := make(chan bool)

go func(doneChan chan bool) {
    defer func() {
        doneChan <- true
    }()

    err := watchFile("/path/to/file")
    if err != nil {
        fmt.Println(err)
    }

    fmt.Println("File has been changed")
}(doneChan)

<-doneChan
Run Code Online (Sandbox Code Playgroud)

不如正确的系统调用那么高效,但它很简单并且可以在任何地方使用,并且可能足以满足某些用途.

  • 这个.我只是无法在后续的文件更改中触发fsnotify(因为它只会触发一次) - 在macos和linux上.这适合我. (2认同)

Tab*_*tha 9

目前的实验包在这里.它应该像os/fsnotifygo1.3 一样合并到核心


小智 8

看看https://github.com/howeyc/fsnotify.它包装Linux内核的inotify子系统,应该在Go1中工作.


pet*_*rSO 6

从Go1开始,inotify已从包中删除.现在看一下syscall包...

Package inotify实现了Linux inotify系统的包装器.

  • 链接(和包似乎)不再存在.你知道它被移到哪里了吗? (2认同)