-
Notifications
You must be signed in to change notification settings - Fork 1
/
signal.go
46 lines (41 loc) · 929 Bytes
/
signal.go
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
package main
import (
"os"
"os/signal"
"sync"
log "github.com/Sirupsen/logrus"
)
// SigHandlerMux watches for kill signals and then executes
// handlers.
type SigHandlerMux struct {
do map[os.Signal][]func()
}
// AddHandler registers a function to one or more signals
func (shm *SigHandlerMux) AddHandler(fn func(), sigs ...os.Signal) {
for _, sig := range sigs {
handlers := append(shm.do[sig], fn)
shm.do[sig] = handlers
}
}
// WatchForSignals monitors for os kill signals and runs arbitrary
// cleanup callbacks before exiting.
func (shm *SigHandlerMux) WatchForSignals() {
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, os.Kill)
for {
select {
case s := <-signals:
log.Warningln("Trapped signal:", s)
wg := sync.WaitGroup{}
for _, fn := range shm.do[s] {
wg.Add(1)
go func(f func()) {
f()
wg.Done()
}(fn)
}
wg.Wait()
os.Exit(1)
}
}
}