signals.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. //go:build linux || darwin
  2. package proc
  3. import (
  4. "os"
  5. "os/signal"
  6. "syscall"
  7. "time"
  8. "github.com/wuntsong-org/go-zero-plus/core/logx"
  9. )
  10. const (
  11. profileDuration = time.Minute
  12. timeFormat = "0102150405"
  13. )
  14. var done = make(chan struct{})
  15. func init() {
  16. go func() {
  17. // https://golang.org/pkg/os/signal/#Notify
  18. signals := make(chan os.Signal, 1)
  19. signal.Notify(signals, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGTERM, syscall.SIGINT)
  20. for {
  21. v := <-signals
  22. switch v {
  23. case syscall.SIGUSR1:
  24. dumpGoroutines(fileCreator{})
  25. case syscall.SIGUSR2:
  26. profiler := StartProfile()
  27. go func() {
  28. <-time.After(profileDuration)
  29. profiler.Stop()
  30. }()
  31. case syscall.SIGTERM:
  32. stopOnSignal()
  33. gracefulStop(signals, syscall.SIGTERM)
  34. case syscall.SIGINT:
  35. stopOnSignal()
  36. gracefulStop(signals, syscall.SIGINT)
  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. }
  47. func stopOnSignal() {
  48. select {
  49. case <-done:
  50. // already closed
  51. default:
  52. close(done)
  53. }
  54. }