File: sighup_watcher.go

package info (click to toggle)
tendermint-go-autofile 0.0~20170129~0git48b17de-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 108 kB
  • ctags: 74
  • sloc: sh: 23; makefile: 4
file content (63 lines) | stat: -rw-r--r-- 1,121 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package autofile

import (
	"os"
	"os/signal"
	"sync"
	"sync/atomic"
	"syscall"
)

func init() {
	initSighupWatcher()
}

var sighupWatchers *SighupWatcher
var sighupCounter int32 // For testing

func initSighupWatcher() {
	sighupWatchers = newSighupWatcher()

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGHUP)

	go func() {
		for _ = range c {
			sighupWatchers.closeAll()
			atomic.AddInt32(&sighupCounter, 1)
		}
	}()
}

// Watchces for SIGHUP events and notifies registered AutoFiles
type SighupWatcher struct {
	mtx       sync.Mutex
	autoFiles map[string]*AutoFile
}

func newSighupWatcher() *SighupWatcher {
	return &SighupWatcher{
		autoFiles: make(map[string]*AutoFile, 10),
	}
}

func (w *SighupWatcher) addAutoFile(af *AutoFile) {
	w.mtx.Lock()
	w.autoFiles[af.ID] = af
	w.mtx.Unlock()
}

// If AutoFile isn't registered or was already removed, does nothing.
func (w *SighupWatcher) removeAutoFile(af *AutoFile) {
	w.mtx.Lock()
	delete(w.autoFiles, af.ID)
	w.mtx.Unlock()
}

func (w *SighupWatcher) closeAll() {
	w.mtx.Lock()
	for _, af := range w.autoFiles {
		af.closeFile()
	}
	w.mtx.Unlock()
}