seaweedfs/weed/util/grace/signal_handling.go

50 lines
779 B
Go
Raw Normal View History

2021-09-01 17:45:42 +08:00
//go:build !plan9
2014-05-14 06:04:04 +08:00
// +build !plan9
package grace
2014-05-14 06:04:04 +08:00
import (
"os"
"os/signal"
"sync"
2014-05-14 06:04:04 +08:00
"syscall"
)
var signalChan chan os.Signal
var hooks = make([]func(), 0)
var hookLock sync.RWMutex
func init() {
signalChan = make(chan os.Signal, 1)
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,
// syscall.SIGHUP,
2014-05-14 06:04:04 +08:00
syscall.SIGINT,
syscall.SIGTERM,
// syscall.SIGQUIT,
)
2014-05-14 06:04:04 +08:00
go func() {
for range signalChan {
hookLock.RLock()
for _, hook := range hooks {
hook()
}
hookLock.RUnlock()
2014-05-14 06:04:04 +08:00
os.Exit(0)
}
}()
}
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)
}