当前位置: 首页>>代码示例>>Golang>>正文


Golang inotify.NewWatcher函数代码示例

本文整理汇总了Golang中golang.org/x/exp/inotify.NewWatcher函数的典型用法代码示例。如果您正苦于以下问题:Golang NewWatcher函数的具体用法?Golang NewWatcher怎么用?Golang NewWatcher使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了NewWatcher函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: watch

func watch(p string, event chan<- EventItem) {
	watcher, err := inotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	dir := path.Dir(p)
	err = watcher.Watch(dir)
	if err != nil {
		log.Fatal(err)
	}

	register(p)

	go func() {
		defer watcher.Close()
		for {
			select {
			case ev := <-watcher.Event:
				if ev.Mask&(inotify.IN_CLOSE_WRITE) > 0 &&
					p == ev.Name {

					event <- diff(p)
				}
			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()
}
开发者ID:ymizushi,项目名称:dnotifier,代码行数:30,代码来源:watcher_linux.go

示例2: Watch

func Watch(restart string, done <-chan struct{}, change func()) error {
	lastStat, err := os.Stat(restart)
	if err != nil {
		return err
	}

	watcher, err := inotify.NewWatcher()
	if err != nil {
		return err
	}

	err = watcher.AddWatch(restart, inotify.IN_ATTRIB|inotify.IN_MODIFY)
	if err != nil {
		return err
	}

	defer watcher.Close()

	for {
		select {
		case <-watcher.Event:
			cur, err := os.Stat(restart)
			if err != nil {
				return err
			}

			if cur.ModTime().After(lastStat.ModTime()) {
				change()
			}
		case <-done:
			return nil
		}
	}
}
开发者ID:y-yagi,项目名称:puma-dev,代码行数:34,代码来源:watch_linux.go

示例3: init

func init() {
	// Generate the reverse of our enum so we can work backwards and reload
	// a file with the name instead of the enum.
	//
	// The issue arises because we've decided to use an array instead of a map
	// to describe our in-memory templates. While this is more efficient, it
	// causes issues with our hot reloading because the name of the file
	// given to us from inotify is the string representation of the file's
	// name, and we can't match that up with the enum on the fly (or generate
	// code that does that using //go: generate). So, we run an init func that
	// generates a map of the names to the enum so we can work backwards to
	// reload the file.
	for i := 0; i < len(_TmplName_index)-1; i++ {
		key := _TmplName_name[_TmplName_index[i]:_TmplName_index[i+1]]
		TmplMap[key] = TmplName(i)
	}

	// Set up our watcher for hot reloads of modified files.
	watcher, err := inotify.NewWatcher()
	if err != nil {
		glog.Fatalln(err)
	}

	err = watcher.Watch(templatePath)
	if err != nil {
		glog.Fatalln(err)
	}

	Tmpls.Watcher = watcher
	Tmpls.Watch()

	cleanup.Register("reload", watcher.Close) // Close watcher.
}
开发者ID:EricLagergren,项目名称:pnwconference,代码行数:33,代码来源:reload.go

示例4: ExampleNewWatcher

func ExampleNewWatcher() {
	watcher, err := inotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case ev := <-watcher.Event:
				//log.Println("event:", ev.Name)
				log.Println("event:", ev.Name, ev.Mask, ev.Cookie)
				log.Println("event:", ev)

			case err := <-watcher.Error:
				log.Println("error:", err)
			}
		}
	}()

	//err = watcher.Add("./testDir")
	//watcher.Watch("/testDir")
	watcher.AddWatch("./testDir", inotify.IN_CLOSE_WRITE)
	if err != nil {
		log.Fatal(err)
	}
	<-done
}
开发者ID:jonahwu,项目名称:lab,代码行数:30,代码来源:not2.go

示例5: main

//watch filesystem, execute command on changes
func main() {
	if len(os.Args) == 3 {
		watchpath = os.Args[1]
		command = os.Args[2]
	} else {
		fmt.Println("Usage: reloader <path> <command> &")
		return
	}
	watcher, err := inotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	err = watcher.Watch(watchpath)
	if err != nil {
		log.Fatal(err)
	}
	log.Println("watching:", watchpath)
	for {
		select {
		case ev := <-watcher.Event:
			if ev.Mask == syscall.IN_CLOSE_WRITE ||
				ev.Mask == syscall.IN_DELETE {
				if hasExt(path.Ext(ev.Name)) {
					log.Println("Reloader:", command)
					doCmd(command)
				}
			}
		case err := <-watcher.Error:
			log.Println("error:", err)
		}
	}
}
开发者ID:jmu0,项目名称:reloader,代码行数:33,代码来源:main.go

示例6: NewWatcher

//NewWatcher creates a new RecursiveWatcher and returns any errors
func NewWatcher() (*RecursiveWatcher, error) {
	watcher, err := inotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	rw := &RecursiveWatcher{watcher: watcher, Event: make(chan *inotify.Event, 100), Error: make(chan error, 10), done: make(chan bool)}

	go func() {
		for {
			select {
			case <-rw.done:
				return
			case event := <-rw.watcher.Event:
				//We need to intercept create events and add watches for them. Removal is handled by inotify on deletion
				if event.Mask&inotify.IN_CREATE == inotify.IN_CREATE || event.Mask&inotify.IN_MOVED_FROM == inotify.IN_MOVED_FROM || event.Mask&inotify.IN_MOVED_TO == inotify.IN_MOVED_TO {
					rw.Watch(event.Name)
				}

				rw.Event <- event
			case err := <-rw.watcher.Error:
				rw.Error <- err
			}
		}
	}()

	return rw, err
}
开发者ID:Jwsonic,项目名称:recinotify,代码行数:29,代码来源:recinotify.go

示例7: start

func (u *NetNSTopoUpdater) start() {
	runtime.LockOSThread()
	defer runtime.UnlockOSThread()

	watcher, err := inotify.NewWatcher()
	if err != nil {
		logging.GetLogger().Error("Unable to create a new Watcher: %s", err.Error())
		return
	}
	err = watcher.Watch(runBaseDir)
	if err != nil {
		logging.GetLogger().Error("Unable to Watch %s: %s", runBaseDir, err.Error())
		return
	}

	u.initialize()

	for {
		select {
		case ev := <-watcher.Event:
			if ev.Mask&inotify.IN_CREATE > 0 {
				u.onNetNsCreated(ev.Name)
			}
			if ev.Mask&inotify.IN_DELETE > 0 {
				u.onNetNsDeleted(ev.Name)
			}

		case err := <-watcher.Error:
			logging.GetLogger().Error("Error while watching network namespace: %s", err.Error())
		}
	}
}
开发者ID:razorinc,项目名称:skydive,代码行数:32,代码来源:netns.go

示例8: main

func main() {
	var stop bool
	sigs := make(chan os.Signal, 1)
	signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)

	watcher, err := inotify.NewWatcher()
	check(err)

	err = watcher.Watch("/tmp")
	check(err)

	for {
		select {
		case ev := <-watcher.Event:
			log.Println("event:", ev)
		case err := <-watcher.Error:
			log.Println("error:", err)
		case <-time.After(time.Second * 1):
			log.Println("-- timeout --")
		case <-sigs:
			log.Println("got signal")
			stop = true
		}

		if true == stop {
			break
		}
	}

	err = watcher.Close()
	check(err)

	log.Println("bye!")
}
开发者ID:mycroft,项目名称:go-snippets,代码行数:34,代码来源:main.go

示例9: NewFeatureMonitor

// NewFeatureMonitor watches the specified state directory, or the default
// state directory if an empty string is given.  The directory must exist.  The
// logger is used for I/O errors, unless nil.
func NewFeatureMonitor(stateDir string, logger Logger) (m *FeatureMonitor, err error) {
	if stateDir == "" {
		stateDir = DefaultStateDir
	}

	featureDir := filepath.Join(stateDir, "features")

	if err = os.Mkdir(featureDir, 0755); err != nil {
		if info, statErr := os.Stat(featureDir); statErr != nil || !info.IsDir() {
			return
		}
		err = nil
	}

	if featureDir, err = filepath.Abs(featureDir); err != nil {
		return
	}

	if featureDir, err = filepath.EvalSymlinks(featureDir); err != nil {
		return
	}

	watcher, err := inotify.NewWatcher()
	if err != nil {
		return
	}

	if err = watcher.AddWatch(featureDir, inotify.IN_ONLYDIR|inotify.IN_CREATE|inotify.IN_DELETE|inotify.IN_DELETE_SELF); err != nil {
		watcher.Close()
		return
	}

	c := make(chan *Feature)
	boot := make(chan struct{})

	m = &FeatureMonitor{
		C:       c,
		Boot:    boot,
		logger:  logger,
		closed:  make(chan struct{}, 1),
		watcher: watcher,
	}

	if infos, err := ioutil.ReadDir(featureDir); err == nil {
		for _, info := range infos {
			m.addFeature(filepath.Join(featureDir, info.Name()))
		}
	} else {
		m.log(err)
	}

	m.queued = append(m.queued, nil) // indicates end of boot

	go m.watchLoop(c, boot, featureDir)

	return
}
开发者ID:ninchat,项目名称:nameq,代码行数:60,代码来源:nameq.go

示例10: eventloop

// eventloop prepares the inotify events and waits for them
func eventloop(mongo MongoInserter) {

	var currentlog LogFileReader

	// open current file
	if logtype == ALPS {
		currentlog = newAlpsLogfile(todayname(), mongo)
	} else {
		currentlog = newTorqueLogfile(todayname(), mongo)
	}
	watcher, err := inotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}

	err = watcher.Watch(config.WatchDirectory)
	if err != nil {
		log.Fatal(err)
	}

	// endless event loop, can be ended by QUIT channel
	for {

		select {

		case ev := <-watcher.Event:
			if (ev.Mask & inotify.IN_CREATE) > 0 {
				// if a file is created, check if it is same file or not, and if it could be
				// todays file
				//if ev.Name != currentlog.name && ev.Name == "testdata/apsched-c2-0c0s0n1-20160820" {
				if ev.Name != currentlog.getName() && ev.Name == todayname() {
					currentlog.readToEnd() // read rest of file in case we missed something
					if logtype == ALPS {
						currentlog = newAlpsLogfile(ev.Name, mongo)
					} else {
						currentlog = newTorqueLogfile(ev.Name, mongo)
					}
				}
			} else if (ev.Mask & inotify.IN_MODIFY) > 0 {
				// if a file is updated, read file to end if it is current file
				if ev.Name == currentlog.getName() {
					currentlog.readToEnd()
				}
			} else {
				// log.Println("inotify event:", ev)
			}

		case err := <-watcher.Error:
			log.Println("inotify error:", err)

		case <-QUIT: // end for testing
			return
		}

	}

}
开发者ID:holgerBerger,项目名称:go_ludalo,代码行数:58,代码来源:batchcollector.go

示例11: NewInotifyWatcher

func NewInotifyWatcher() (*InotifyWatcher, error) {
	w, err := inotify.NewWatcher()
	if err != nil {
		return nil, err
	}

	return &InotifyWatcher{
		watcher:           w,
		containersWatched: make(map[string]map[string]bool),
	}, nil
}
开发者ID:RomainVabre,项目名称:origin,代码行数:11,代码来源:inotify_watcher.go

示例12: inotifySetup

func inotifySetup(dir string) *inotify.Watcher {
	watcher, err := inotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	err = watcher.Watch(dir)
	if err != nil {
		log.Fatal(err)
	}

	return watcher
}
开发者ID:ngavalas,项目名称:csl-replay-parser,代码行数:12,代码来源:main.go

示例13: main

func main() {

	configFile := flag.String("c", "config.toml", "Config file path")
	flag.Parse()

	findSocatBinary()

	services := parseConfig(*configFile)

	for _, s := range services {
		if !s.Enabled {
			log.Println(fmt.Sprintf("Service %s is disabled", s.Name))
		} else {
			s.Start()
		}
	}

	var watch *inotify.Watcher
	var err error
	if watch, err = inotify.NewWatcher(); err != nil {
		log.Println(fmt.Sprintf("Could not create a watcher: %s. Changes will need a restart to become effective", err))
	} else {
		setWatch(watch, filepath.Dir(*configFile))
	}

	for {
		select {
		case ev := <-watch.Event:
			if filepath.Base(ev.Name) == *configFile {
				log.Println("Change on the config file detected. Reloading services...")

				unsetWatch(watch, filepath.Dir(*configFile))

				for _, s := range services {
					s.Stop()
				}

				<-time.NewTimer(time.Millisecond * 500).C
				services = parseConfig(*configFile)

				for _, s := range services {
					if !s.Enabled {
						log.Println(fmt.Sprintf("Service %s is disabled", s.Name))
					} else {
						s.Start()
					}
				}
				setWatch(watch, filepath.Dir(*configFile))
			}
		}
	}
}
开发者ID:pho,项目名称:socatgun,代码行数:52,代码来源:main.go

示例14: NewTail

// NewTail starts opens the given file and watches it for deletion/rotation
func NewTail(filename string) (*Tail, error) {
	t := &Tail{
		filename: filename,
	}
	var err error
	t.stop = make(chan bool)
	t.watcher, err = inotify.NewWatcher()
	if err != nil {
		return nil, fmt.Errorf("inotify init failed on %s: %v", t.filename, err)
	}
	go t.watchLoop()
	return t, nil
}
开发者ID:40a,项目名称:bootkube,代码行数:14,代码来源:tail.go

示例15: watchDir

func (b *builder) watchDir(ctx context.Context, dir string, f func(*inotify.Event)) error {
	infos, err := ioutil.ReadDir(dir)
	if err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	errc := make(chan error)
	for _, info := range infos {
		if !info.IsDir() {
			continue
		}
		go func(info os.FileInfo) {
			fn := func(ev *inotify.Event) {
				ev.Name = filepath.Join(dir, ev.Name)
				f(ev)
			}
			select {
			case errc <- b.watchDir(ctx, filepath.Join(dir, info.Name()), fn):
			case <-ctx.Done():
			}
		}(info)
	}

	w, err := inotify.NewWatcher()
	if err != nil {
		return err
	}
	defer w.Close()
	if err := w.AddWatch(dir, flags); err != nil {
		return err
	}
	for {
		select {
		case ev := <-w.Event:
			if ignore(ev.Name) {
				continue
			}
			f(ev)
		case err := <-w.Error:
			return err
		case err := <-errc:
			return err
		case <-ctx.Done():
			return ctx.Err()
		}
	}
}
开发者ID:ericchiang,项目名称:blog,代码行数:50,代码来源:watch.go


注:本文中的golang.org/x/exp/inotify.NewWatcher函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。