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.

69 lines
1.2 KiB

8 years ago
8 years ago
8 years ago
8 years ago
  1. package autofile
  2. import (
  3. "os"
  4. "os/signal"
  5. "sync"
  6. "sync/atomic"
  7. "syscall"
  8. )
  9. func init() {
  10. initSighupWatcher()
  11. }
  12. var sighupWatchers *SighupWatcher
  13. var sighupCounter int32 // For testing
  14. func initSighupWatcher() {
  15. sighupWatchers = newSighupWatcher()
  16. hup := make(chan os.Signal, 1)
  17. signal.Notify(hup, syscall.SIGHUP)
  18. quit := make(chan os.Signal, 1)
  19. signal.Notify(quit, os.Interrupt, syscall.SIGTERM)
  20. go func() {
  21. select {
  22. case <-hup:
  23. sighupWatchers.closeAll()
  24. atomic.AddInt32(&sighupCounter, 1)
  25. case <-quit:
  26. return
  27. }
  28. }()
  29. }
  30. // Watchces for SIGHUP events and notifies registered AutoFiles
  31. type SighupWatcher struct {
  32. mtx sync.Mutex
  33. autoFiles map[string]*AutoFile
  34. }
  35. func newSighupWatcher() *SighupWatcher {
  36. return &SighupWatcher{
  37. autoFiles: make(map[string]*AutoFile, 10),
  38. }
  39. }
  40. func (w *SighupWatcher) addAutoFile(af *AutoFile) {
  41. w.mtx.Lock()
  42. w.autoFiles[af.ID] = af
  43. w.mtx.Unlock()
  44. }
  45. // If AutoFile isn't registered or was already removed, does nothing.
  46. func (w *SighupWatcher) removeAutoFile(af *AutoFile) {
  47. w.mtx.Lock()
  48. delete(w.autoFiles, af.ID)
  49. w.mtx.Unlock()
  50. }
  51. func (w *SighupWatcher) closeAll() {
  52. w.mtx.Lock()
  53. for _, af := range w.autoFiles {
  54. af.closeFile()
  55. }
  56. w.mtx.Unlock()
  57. }