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.

46 lines
721 B

11 years ago
  1. // +build !plan9
  2. package grace
  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. }