-
Notifications
You must be signed in to change notification settings - Fork 248
/
signal.go
59 lines (46 loc) · 1.15 KB
/
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
47
48
49
50
51
52
53
54
55
56
57
58
59
package daemon
import (
"errors"
"os"
"os/signal"
"syscall"
)
// ErrStop should be returned signal handler function
// for termination of handling signals.
var ErrStop = errors.New("stop serve signals")
// SignalHandlerFunc is the interface for signal handler functions.
type SignalHandlerFunc func(sig os.Signal) (err error)
// SetSigHandler sets handler for the given signals.
// SIGTERM has the default handler, he returns ErrStop.
func SetSigHandler(handler SignalHandlerFunc, signals ...os.Signal) {
for _, sig := range signals {
handlers[sig] = handler
}
}
// ServeSignals calls handlers for system signals.
func ServeSignals() (err error) {
signals := make([]os.Signal, 0, len(handlers))
for sig := range handlers {
signals = append(signals, sig)
}
ch := make(chan os.Signal, 8)
signal.Notify(ch, signals...)
for sig := range ch {
err = handlers[sig](sig)
if err != nil {
break
}
}
signal.Stop(ch)
if err == ErrStop {
err = nil
}
return
}
var handlers = make(map[os.Signal]SignalHandlerFunc)
func init() {
handlers[syscall.SIGTERM] = sigtermDefaultHandler
}
func sigtermDefaultHandler(sig os.Signal) error {
return ErrStop
}