-
Notifications
You must be signed in to change notification settings - Fork 200
/
interrupt.go
54 lines (47 loc) · 1.02 KB
/
interrupt.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
package workspace
import (
"github.com/qiniu/qshell/v2/iqshell/common/data"
"github.com/qiniu/qshell/v2/iqshell/common/log"
"os"
"os/signal"
"sync"
"sync/atomic"
)
var (
// 程序是否退出
isCmdInterrupt uint32 = 0
locker sync.Mutex
cancelObservers = make([]func(s os.Signal), 0)
)
func AddCancelObserver(observer func(s os.Signal)) {
if observer == nil {
return
}
locker.Lock()
cancelObservers = append(cancelObservers, observer)
locker.Unlock()
}
func notifyCancelSignalToObservers(s os.Signal) {
locker.Lock()
for _, observer := range cancelObservers {
observer(s)
}
locker.Unlock()
}
func IsCmdInterrupt() bool {
return atomic.LoadUint32(&isCmdInterrupt) > 0
}
func observerCmdInterrupt() {
s := make(chan os.Signal, 1)
signal.Notify(s, os.Interrupt, os.Kill)
go func() {
si := <-s
log.Alert("")
log.DebugF("Got signal:%s", si)
atomic.StoreUint32(&isCmdInterrupt, 1)
data.SetCmdStatusUserCancel()
Cancel()
notifyCancelSignalToObservers(si)
os.Exit(data.StatusUserCancel)
}()
}