首页 > 代码库 > go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变
go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变
package main import ( "fmt" "time" "os/exec" "strings" "io/ioutil" "os" "github.com/howeyc/fsnotify" ) const filePath = "/home/ubuntu/GzhuOJ/public" var watcher *fsnotify.Watcher func Print(args ...interface{}) { fmt.Println(time.Now(), args) } func isDir(path string) bool { fileInfo, err := os.Stat(path) if err != nil { Print("error:", err.Error()) return false } return fileInfo.IsDir() } func watchPath(filePath string) { Print("watchPath:", filePath) err := watcher.Watch(filePath) if err != nil { Print(err.Error()) return } } func broweDir(path string) { Print("broweDir:", path) dir, err := os.Open(path) if err != nil { Print("error:", err.Error()) return } defer dir.Close() names, err := dir.Readdirnames(-1) if err != nil { Print("error:", err.Error()) return } for _, name := range names { dirPath := path + "/" + name if !isDir(dirPath) { continue } watchPath(dirPath) broweDir(dirPath) } } func main() { var err error watcher, err = fsnotify.NewWatcher() if err != nil { panic(err) } defer watcher.Close() broweDir(filePath) watchPath(filePath) dealWatch() } func dealWatch() { for { select { case event := <-watcher.Event: Print("event: ", event) if !event.IsModify() && !event.IsCreate() { break } cmd := exec.Command("scp", "-r", "-P 23456", filePath+strings.TrimPrefix(event.Name, filePath), "root@emb.mobi:/home/public") Print("cmd:", cmd.Args) stderr, err := cmd.StderrPipe() if err != nil { Print(err.Error()) break } stdout, err := cmd.StdoutPipe() if err != nil { Print(err.Error()) break } if err = cmd.Start(); err != nil { Print(err.Error()) break } errBytes, err := ioutil.ReadAll(stderr) if err != nil { Print(err.Error()) break } outBytes, err := ioutil.ReadAll(stdout) if err != nil { Print(err.Error()) break } if len(errBytes) != 0 { Print("errors:", string(errBytes)) } if len(outBytes) != 0 { Print("output:", string(outBytes)) } case err := <-watcher.Error: Print("error: ", err.Error()) } } }
要注意的是一个fsnotify.Watcher能watch多个文件和文件夹
go监视文件改变实现同步--包含遍历文件夹,执行cmd命令,检测文件改变
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。