This repository has been archived by the owner on Mar 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
signals.go
executable file
·100 lines (81 loc) · 2.17 KB
/
signals.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/*
* Copyright © 2019 Hedzr Yeh.
*/
package sig
import (
"gopkg.in/hedzr/errors.v2"
"log"
"net"
"os"
"os/signal"
)
// ServeSignals calls handlers for system signals.
// before invoking ServeSignals(), you should run SetupSignals() at first.
func ServeSignals() (err error) {
if len(handlers) == 0 {
setupSignals()
}
if len(handlers) == 0 {
return // no handlers, skip the os signal listening
}
// syscall.Getenv()
signals := makeHandlers()
// defer func() {
// removePID(ctx)
// }()
//
// log.Printf("serve signals ... pid: %v in %v", os.Getpid(), ctx.PidFileName)
ch := make(chan os.Signal, 8)
signal.Notify(ch, signals...)
for sig := range ch {
log.Printf(".. signal caught: %v", sig)
err = handlers[sig](sig)
if err != nil {
break
}
}
signal.Stop(ch)
if err == ErrStop {
err = nil
}
return
}
// HandleSignalCaughtEvent is a shortcut to block the main business logic loop but break it if os signals caught.
// `stop` channel will be trigger if any hooked os signal caught, such as os.Interrupt;
// the main business logic loop should trigger `done` once `stop` holds.
func HandleSignalCaughtEvent() bool {
select {
case <-stop:
log.Print("stop ch received. send done ch.")
done <- struct{}{}
return true
default:
return false
}
}
// GetChs returns the standard `stop`, `done` channel
func GetChs() (stopCh, doneCh chan struct{}) {
stopCh, doneCh = stop, done
return
}
var (
// ErrStop should be returned signal handler function
// for termination of handling signals.
ErrStop = errors.New("stop serve signals")
handlers = make(map[os.Signal]SignalHandlerFunc)
// child *os.Process
onSetTermHandler func() []os.Signal
onSetSigEmtHandler func() []os.Signal
onSetReloadHandler func() []os.Signal
onSetHotReloadHandler func() []os.Signal
onGetListener func() net.Listener
stop = make(chan struct{})
done = make(chan struct{})
)
const (
// ErrnoForkAndDaemonFailed is os errno when daemon plugin and its impl occurs errors.
ErrnoForkAndDaemonFailed = -1
envvarInDaemonized = "__DAEMON"
)
// SignalHandlerFunc is the interface for signal handler functions.
type SignalHandlerFunc func(sig os.Signal) (err error)