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.

63 lines
1.1 KiB

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. c := make(chan os.Signal, 1)
  17. signal.Notify(c, syscall.SIGHUP)
  18. go func() {
  19. for range c {
  20. sighupWatchers.closeAll()
  21. atomic.AddInt32(&sighupCounter, 1)
  22. }
  23. }()
  24. }
  25. // Watchces for SIGHUP events and notifies registered AutoFiles
  26. type SighupWatcher struct {
  27. mtx sync.Mutex
  28. autoFiles map[string]*AutoFile
  29. }
  30. func newSighupWatcher() *SighupWatcher {
  31. return &SighupWatcher{
  32. autoFiles: make(map[string]*AutoFile, 10),
  33. }
  34. }
  35. func (w *SighupWatcher) addAutoFile(af *AutoFile) {
  36. w.mtx.Lock()
  37. w.autoFiles[af.ID] = af
  38. w.mtx.Unlock()
  39. }
  40. // If AutoFile isn't registered or was already removed, does nothing.
  41. func (w *SighupWatcher) removeAutoFile(af *AutoFile) {
  42. w.mtx.Lock()
  43. delete(w.autoFiles, af.ID)
  44. w.mtx.Unlock()
  45. }
  46. func (w *SighupWatcher) closeAll() {
  47. w.mtx.Lock()
  48. for _, af := range w.autoFiles {
  49. af.closeFile()
  50. }
  51. w.mtx.Unlock()
  52. }