signal_handling.go 720 B

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