Go to file
lovezsh 8d5162e996 change module name 2020-12-05 10:53:08 +08:00
example fixed: error 2020-05-26 10:48:34 +08:00
README.md fixed: error 2020-05-26 10:48:34 +08:00
go.mod change module name 2020-12-05 10:53:08 +08:00
go.sum init 2020-05-26 10:47:00 +08:00
inotify.go init 2020-05-26 10:47:00 +08:00
poller.go init 2020-05-26 10:47:00 +08:00
poller_test.go init 2020-05-26 10:47:00 +08:00

README.md

简介

Linux Inotify API的封装。

使用示例

package main

import (
        "fmt"
        "inotify"
        "log"
        "os"
        "path/filepath"
        "time"
)

func main() {
        watcher, err := inotify.NewWatcher()
        if err != nil {
                log.Println(err)
        }
        name := os.Args[1]
        paths := make([]string, 0)
        if !isExistDir(name) {
                paths = append(paths, name)
        } else {
                var err error
                paths, err = dirs(name)
                if err != nil {
                        log.Fatal(err)
                }
        }
        for _, v := range paths {
                err = watcher.AddWatch(v)
                if err != nil {
                        log.Fatalf("failed to add watch %s, error: %v\n", os.Args[1], err)
                }
        }

        ticker := time.NewTicker(3 * time.Second)
        for {
                select {
                case err := <-watcher.Errors:
                        log.Println(err)
                        os.Exit(1)
                case event := <-watcher.Events:
                        if event.IsDir {
                                if event.Name == inotify.EventCreate {
                                        err = watcher.AddWatch(event.Path)
                                        if err != nil {
                                                log.Fatalf("failed to add watch %s, error: %v\n", event.Path, err)
                                        }
                                }
                                fmt.Println("Directory:", event.Path, "event:", event.Name)
                        } else {
                                fmt.Println("File:", event.Path, "event:", event.Name)
                        }
                case <-ticker.C:
                        fmt.Println(watcher.Path())
                }
        }
}

func isExistDir(name string) bool {
        f, err := os.Stat(name)
        return err == nil && f.IsDir()
}

func dirs(name string) ([]string, error) {
        matchs := make([]string, 0)
        err := filepath.Walk(name, func(root string, info os.FileInfo, err error) error {
                if err != nil {
                        return err
                }
                if info.IsDir() {
                        matchs = append(matchs, root)
                }
                return nil
        })
        return matchs, err
}