-
Notifications
You must be signed in to change notification settings - Fork 0
/
exit.go
103 lines (90 loc) · 1.34 KB
/
exit.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
101
102
103
package exit
import (
"github.com/gozelle/logger"
"os"
"os/signal"
"sync"
"syscall"
)
var (
signals = make(chan os.Signal, 1)
cleanFns []func() error
lock = sync.Mutex{}
pid int
)
var log = logger.NewLogger("exit")
func init() {
pid = os.Getpid()
signal.Notify(signals, os.Interrupt, os.Kill, syscall.SIGINT, syscall.SIGTERM)
}
func PID() int {
return pid
}
func clean() (err error) {
lock.Lock()
defer lock.Unlock()
for _, handler := range cleanFns {
err = handler()
if err != nil {
return
}
}
return
}
func Clean(fn func()) {
lock.Lock()
defer lock.Unlock()
cleanFns = append(cleanFns, func() error {
fn()
return nil
})
}
func Handle(fn func() error) {
lock.Lock()
defer lock.Unlock()
cleanFns = append(cleanFns, fn)
}
func Pid() int {
return pid
}
func Exit() {
signals <- os.Interrupt
}
func exit() (ok bool) {
log.Infof("exiting...")
err := clean()
if err != nil {
log.Errorf("exit failed : %s", err)
return
}
ok = true
return
}
func Signal() chan struct{} {
s := make(chan struct{})
go func() {
for {
select {
case <-signals:
if exit() {
s <- struct{}{}
log.Infof("trigger exit signal")
return
}
}
}
}()
return s
}
func Wait() {
for {
select {
case <-signals:
if exit() {
log.Infof("exit success")
close(signals)
os.Exit(0)
}
}
}
}