OSDN Git Service

new repo
[bytom/vapor.git] / vendor / github.com / tendermint / tmlibs / autofile / sighup_watcher.go
1 package autofile
2
3 import (
4         "os"
5         "os/signal"
6         "sync"
7         "sync/atomic"
8         "syscall"
9 )
10
11 func init() {
12         initSighupWatcher()
13 }
14
15 var sighupWatchers *SighupWatcher
16 var sighupCounter int32 // For testing
17
18 func initSighupWatcher() {
19         sighupWatchers = newSighupWatcher()
20
21         c := make(chan os.Signal, 1)
22         signal.Notify(c, syscall.SIGHUP)
23
24         go func() {
25                 for range c {
26                         sighupWatchers.closeAll()
27                         atomic.AddInt32(&sighupCounter, 1)
28                 }
29         }()
30 }
31
32 // Watchces for SIGHUP events and notifies registered AutoFiles
33 type SighupWatcher struct {
34         mtx       sync.Mutex
35         autoFiles map[string]*AutoFile
36 }
37
38 func newSighupWatcher() *SighupWatcher {
39         return &SighupWatcher{
40                 autoFiles: make(map[string]*AutoFile, 10),
41         }
42 }
43
44 func (w *SighupWatcher) addAutoFile(af *AutoFile) {
45         w.mtx.Lock()
46         w.autoFiles[af.ID] = af
47         w.mtx.Unlock()
48 }
49
50 // If AutoFile isn't registered or was already removed, does nothing.
51 func (w *SighupWatcher) removeAutoFile(af *AutoFile) {
52         w.mtx.Lock()
53         delete(w.autoFiles, af.ID)
54         w.mtx.Unlock()
55 }
56
57 func (w *SighupWatcher) closeAll() {
58         w.mtx.Lock()
59         for _, af := range w.autoFiles {
60                 af.closeFile()
61         }
62         w.mtx.Unlock()
63 }