2021-09-01 17:45:42 +08:00
|
|
|
//go:build !plan9
|
2014-05-14 06:04:04 +08:00
|
|
|
// +build !plan9
|
|
|
|
|
2020-04-28 14:10:23 +08:00
|
|
|
package grace
|
2014-05-14 06:04:04 +08:00
|
|
|
|
|
|
|
import (
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
2018-10-09 15:41:57 +08:00
|
|
|
"sync"
|
2014-05-14 06:04:04 +08:00
|
|
|
"syscall"
|
|
|
|
)
|
|
|
|
|
2018-10-09 15:41:57 +08:00
|
|
|
var signalChan chan os.Signal
|
|
|
|
var hooks = make([]func(), 0)
|
2022-09-02 04:08:34 +08:00
|
|
|
var hookLock sync.Mutex
|
2018-10-09 15:41:57 +08:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
signalChan = make(chan os.Signal, 1)
|
2015-10-19 14:39:11 +08:00
|
|
|
signal.Ignore(syscall.SIGHUP)
|
2014-05-14 06:04:04 +08:00
|
|
|
signal.Notify(signalChan,
|
|
|
|
os.Interrupt,
|
|
|
|
os.Kill,
|
2014-05-14 10:26:05 +08:00
|
|
|
syscall.SIGALRM,
|
2015-10-19 14:39:11 +08:00
|
|
|
// syscall.SIGHUP,
|
2014-05-14 06:04:04 +08:00
|
|
|
syscall.SIGINT,
|
|
|
|
syscall.SIGTERM,
|
2016-04-14 16:30:26 +08:00
|
|
|
// syscall.SIGQUIT,
|
|
|
|
)
|
2014-05-14 06:04:04 +08:00
|
|
|
go func() {
|
2022-09-02 04:08:34 +08:00
|
|
|
for _ = range signalChan {
|
2018-10-09 15:41:57 +08:00
|
|
|
for _, hook := range hooks {
|
|
|
|
hook()
|
|
|
|
}
|
2014-05-14 06:04:04 +08:00
|
|
|
os.Exit(0)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
}
|
2018-10-09 15:41:57 +08:00
|
|
|
|
|
|
|
func OnInterrupt(fn func()) {
|
|
|
|
// prevent reentry
|
|
|
|
hookLock.Lock()
|
|
|
|
defer hookLock.Unlock()
|
|
|
|
|
|
|
|
// deal with control+c,etc
|
|
|
|
// controlling terminal close, daemon not exit
|
|
|
|
hooks = append(hooks, fn)
|
|
|
|
}
|