signal_handling.go 739 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. //go:build !plan9
  2. // +build !plan9
  3. package grace
  4. import (
  5. "os"
  6. "os/signal"
  7. "sync"
  8. "syscall"
  9. )
  10. var signalChan chan os.Signal
  11. var hooks = make([]func(), 0)
  12. var hookLock sync.Mutex
  13. func init() {
  14. signalChan = make(chan os.Signal, 1)
  15. signal.Ignore(syscall.SIGHUP)
  16. signal.Notify(signalChan,
  17. os.Interrupt,
  18. os.Kill,
  19. syscall.SIGALRM,
  20. // syscall.SIGHUP,
  21. syscall.SIGINT,
  22. syscall.SIGTERM,
  23. // syscall.SIGQUIT,
  24. )
  25. go func() {
  26. for _ = range signalChan {
  27. for _, hook := range hooks {
  28. hook()
  29. }
  30. os.Exit(0)
  31. }
  32. }()
  33. }
  34. func OnInterrupt(fn func()) {
  35. // prevent reentry
  36. hookLock.Lock()
  37. defer hookLock.Unlock()
  38. // deal with control+c,etc
  39. // controlling terminal close, daemon not exit
  40. hooks = append(hooks, fn)
  41. }