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
64
65
66
67
68
69
70
|
package main
import (
"fmt"
"os"
"os/signal"
)
// OnSignalCB callback type for signal
type OnSignalCB func(sig os.Signal)
// MonSignals .
type MonSignals struct {
callback map[string][]OnSignalCB
registeredSignals []os.Signal
}
var monSig MonSignals
// MonitorSignals Routine used to monitor signals (eg. SIGINT, SIGTERM, ...)
func MonitorSignals() {
monSig.callback = make(map[string][]OnSignalCB)
monSig.registeredSignals = GetRegisteredSignals()
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, monSig.registeredSignals...)
go func() {
for {
sig := <-sigs
Log.Debugf("Detect signal %v", sig)
if cbArr, exist := monSig.callback[sig.String()]; exist {
for _, cb := range cbArr {
cb(sig)
}
}
}
}()
}
// isSupportSignal Check if a signal is supported or not
func isSupportSignal(sig os.Signal) bool {
for _, s := range monSig.registeredSignals {
if s == sig {
return true
}
}
return false
}
// OnSignal Register a callback for a specified signal
func OnSignal(sig os.Signal, fCB OnSignalCB) error {
if !isSupportSignal(sig) {
return fmt.Errorf("unsupported signal %v", sig)
}
sigStr := sig.String()
monSig.callback[sigStr] = append(monSig.callback[sigStr], fCB)
return nil
}
// OnSignals Register a callback for any signals
func OnSignals(fCB OnSignalCB) error {
for _, s := range monSig.registeredSignals {
if err := OnSignal(s, fCB); err != nil {
return err
}
}
return nil
}
|