Guest User

Untitled

a guest
Nov 12th, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. package main
  2.  
  3. var (
  4. ctx context.Context
  5. cancel func()
  6. )
  7.  
  8. func main() {
  9. ctx, cancel := context.WithCancel(context.Background)
  10. defer cancel() // ensures on exit the routines are shut
  11.  
  12. // waits for ^c in the background
  13. go interruptWatcher()
  14.  
  15. // waits for file changes in /tmp or for context cancel
  16. watch(ctx)
  17. }
  18.  
  19. func watch(ctx context.Context) {
  20. events := make(chan notify.EventInfo, 1)
  21.  
  22. notify.Watch("/tmp", events, notify.InDelete, notify.InCloseWrite, notify.InMovedTo)
  23.  
  24. for {
  25. select {
  26. case event := <-events:
  27. fmt.Printf("Handling event %#v\n", event)
  28. case <-ctx.Done(): // ^c notifies on this and we know to exit
  29. notify.Stop(events)
  30. return
  31. }
  32. }
  33. }
  34.  
  35. func interruptWatcher() {
  36. sigs := make(chan os.Signal, 1)
  37. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
  38.  
  39. for {
  40. select {
  41. case sig := <-sigs:
  42. switch sig {
  43. case syscall.SIGINT, syscall.SIGTERM:
  44. fmt.Printf("Shutting down on %s", sig)
  45. cancel()
  46. }
  47. case <-ctx.Done():
  48. return
  49. }
  50. }
  51. }
Add Comment
Please, Sign In to add comment