专栏名称: 狗厂
51好读  ›  专栏  ›  狗厂

gobox中处理文件系统通知

狗厂  · 掘金  ·  · 2018-07-18 06:19

正文

今天来说下使用gobox中inotify来处理文件系统通知

inotify介绍

inotify是linux系统的文件事件通知机制,例如我们想得知某个文件是否被改变,目录的读写情况等,都可以使用这个机制。

用法示例

package main

import (
	"github.com/goinbox/inotify"

	"fmt"
	"path/filepath"
)

func main() {
	path := "/tmp/a.log"

	watcher, _ := inotify.NewWatcher()
	watcher.AddWatch(path, inotify.IN_ALL_EVENTS)
	watcher.AddWatch(filepath.Dir(path), inotify.IN_ALL_EVENTS)

	for i := 0; i < 5; i++ {
		events, _ := watcher.ReadEvents()
		for _, event := range events {
			if watcher.IsUnreadEvent(event) {
				fmt.Println("it is a last remaining event")
			}
			showEvent(event)
		}
	}

	watcher.Free()
	fmt.Println("bye")
}

func showEvent(event *inotify.Event) {
	fmt.Println(event)

	if event.InIgnored() {
		fmt.Println("inotify.IN_IGNORED")
	}

	if event.InAttrib() {
		fmt.Println("inotify.IN_ATTRIB")
	}

	if event.InModify() {
		fmt.Println("inotify.IN_MODIFY")
	}

	if event.InMoveSelf() {
		fmt.Println("inotify.IN_MOVE_SELF")
	}

	if event.InMovedFrom() {
		fmt.Println("inotify.IN_MOVED_FROM")
	}

	if event.InMovedTo() {
		fmt.Println("inotify.IN_MOVED_TO")
	}

	if event.InDeleteSelf() {
		fmt.Println("inotify.IN_DELETE_SELF")
	}

	if event.InDelete() {
		fmt.Println("inotify.IN_DELETE")
	}

	if event.InCreate() {
		fmt.Println("inotify.IN_CREATE")
	}
}

如示例,我们监听了 /tmp/a.log /tmp 目录的文件系统事件。







请到「今天看啥」查看全文