signals.go 968 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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)
  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. select {
  31. case <-done:
  32. // already closed
  33. default:
  34. close(done)
  35. }
  36. gracefulStop(signals)
  37. default:
  38. logx.Error("Got unregistered signal:", v)
  39. }
  40. }
  41. }()
  42. }
  43. // Done returns the channel that notifies the process quitting.
  44. func Done() <-chan struct{} {
  45. return done
  46. }