博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Go] 跨平台文件系统监控工具 fsnotify 应用举例
阅读量:5109 次
发布时间:2019-06-13

本文共 2168 字,大约阅读时间需要 7 分钟。

项目地址:

fsnotify 能监控指定文件夹内 文件的修改情况,如 文件的 增加、删除、修改、重命名等操作。

官方给出了以下注意事项:

When a file is moved to another directory is it still being watched?

No (it shouldn't be, unless you are watching where it was moved to).

When I watch a directory, are all subdirectories watched as well?

No, you must add watches for any directory you want to watch (a recursive watcher is on the roadmap ).

Do I have to watch the Error and Event channels in a separate goroutine?

As of now, yes. Looking into making this single-thread friendly (see )

Why am I receiving multiple events for the same file on OS X?

Spotlight indexing on OS X can result in multiple events (see ). A temporary workaround is to add your folder(s) to the Spotlight Privacy settings until we have a native FSEvents implementation (see ).

How many files can be watched at once?

There are OS-specific limits as to how many watches can be created:

  • Linux: /proc/sys/fs/inotify/max_user_watches contains the limit, reaching this limit results in a "no space left on device" error.
  • BSD / OSX: sysctl variables "kern.maxfiles" and "kern.maxfilesperproc", reaching these limits results in a "too many open files" error.

最为注意的一点是:

文件夹中的子文件夹,还需自己去添加监控,fsnotify 本身不提供递归循环监控功能!

应用举例

package mainimport (	"github.com/fsnotify/fsnotify"	"log"	"runtime")func main() {	// 监控路径列表	paths := []string{		"/Users/jianbao/GoglandProjects/fiisoo/src/test/ch0",		"/Users/jianbao/GoglandProjects/fiisoo/src/test/ch1",	}	watcher, err := fsnotify.NewWatcher()	if err != nil {		log.Fatalf("Failed to create watcher: %s", err)	}	defer watcher.Close()	exit := make(chan bool)	go func() {		for {			select {			case e := <-watcher.Events:				log.Println("修改文件:" + e.Name)				log.Println("修改类型:" + e.Op.String())			case err := <-watcher.Errors:				log.Printf("Watcher error: %s\n", err.Error()) // No need to exit here			}		}	}()	log.Println("Initializing watcher...")	for _, path := range paths {		log.Printf("Watching: %s\n", path)		err = watcher.Add(path)		if err != nil {			log.Fatalf("Failed to watch directory: %s", err)		}	}	<-exit // 用来 阻塞应用不退出,只能通过“杀死进程”的方式退出,如 按住 Ctrl + C 快捷键强制推出	runtime.Goexit()}

转载于:https://www.cnblogs.com/52php/p/6794962.html

你可能感兴趣的文章
观察者模式
查看>>
转】MyEclipse使用总结——MyEclipse文件查找技巧
查看>>
Weka中数据挖掘与机器学习系列之基本概念(三)
查看>>
Java-文件上传和下载
查看>>
Memory and Trident(CodeForces 712B)
查看>>
Win磁盘MBR转换为GUID
查看>>
大家在做.NET B/S项目的时候多用什么设技术啊?
查看>>
投资策略 ——摘自凤凰网
查看>>
Java SE和Java EE应用的性能调优
查看>>
Android设计模式系列--原型模式
查看>>
spring boot 整合 云之讯 demo
查看>>
CoolBlog开发笔记第4课:数据库模型设计
查看>>
翻译:给19岁有志青年的建议 Advice for ambitious 19 year olds
查看>>
DenyHosts 阻止SSH暴力攻击
查看>>
java001-Helloworld
查看>>
免费的论文查重网站
查看>>
C语言程序第一次作业
查看>>
leetcode-Sort List
查看>>
常用的Javascript设计模式
查看>>
静态库
查看>>