signals.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. //go:build linux || darwin
  2. package proc
  3. import (
  4. "os"
  5. "os/signal"
  6. "syscall"
  7. "github.com/zeromicro/go-zero/core/logx"
  8. )
  9. const timeFormat = "0102150405"
  10. var done = make(chan struct{})
  11. func init() {
  12. go func() {
  13. var profiler Stopper
  14. // https://golang.org/pkg/os/signal/#Notify
  15. signals := make(chan os.Signal, 1)
  16. signal.Notify(signals, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGTERM, syscall.SIGINT)
  17. for {
  18. v := <-signals
  19. switch v {
  20. case syscall.SIGUSR1:
  21. dumpGoroutines(fileCreator{})
  22. case syscall.SIGUSR2:
  23. if profiler == nil {
  24. profiler = StartProfile()
  25. } else {
  26. profiler.Stop()
  27. profiler = nil
  28. }
  29. case syscall.SIGTERM:
  30. stopOnSignal()
  31. gracefulStop(signals, syscall.SIGTERM)
  32. case syscall.SIGINT:
  33. stopOnSignal()
  34. gracefulStop(signals, syscall.SIGINT)
  35. default:
  36. logx.Error("Got unregistered signal:", v)
  37. }
  38. }
  39. }()
  40. }
  41. // Done returns the channel that notifies the process quitting.
  42. func Done() <-chan struct{} {
  43. return done
  44. }
  45. func stopOnSignal() {
  46. select {
  47. case <-done:
  48. // already closed
  49. default:
  50. close(done)
  51. }
  52. }