signals.go 977 B

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