You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
779 B

3 years ago
11 years ago
  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.RWMutex
  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. hookLock.RLock()
  28. for _, hook := range hooks {
  29. hook()
  30. }
  31. hookLock.RUnlock()
  32. os.Exit(0)
  33. }
  34. }()
  35. }
  36. func OnInterrupt(fn func()) {
  37. // prevent reentry
  38. hookLock.Lock()
  39. defer hookLock.Unlock()
  40. // deal with control+c,etc
  41. // controlling terminal close, daemon not exit
  42. hooks = append(hooks, fn)
  43. }