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.

47 lines
739 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.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. }