go-zero/core/proc/signals.go

61 lines
1.1 KiB
Go
Raw Normal View History

//go:build linux || darwin
2020-07-26 17:09:05 +08:00
package proc
import (
"os"
"os/signal"
"syscall"
"time"
2020-07-26 17:09:05 +08:00
"github.com/zeromicro/go-zero/core/logx"
2020-07-26 17:09:05 +08:00
)
const (
profileDuration = time.Minute
timeFormat = "0102150405"
)
2020-07-26 17:09:05 +08:00
var done = make(chan struct{})
2020-07-26 17:09:05 +08:00
func init() {
go func() {
// https://golang.org/pkg/os/signal/#Notify
signals := make(chan os.Signal, 1)
signal.Notify(signals, syscall.SIGUSR1, syscall.SIGUSR2, syscall.SIGTERM, syscall.SIGINT)
2020-07-26 17:09:05 +08:00
for {
v := <-signals
switch v {
case syscall.SIGUSR1:
2023-06-12 01:22:20 +08:00
dumpGoroutines(fileCreator{})
2020-07-26 17:09:05 +08:00
case syscall.SIGUSR2:
profiler := StartProfile()
time.AfterFunc(profileDuration, profiler.Stop)
case syscall.SIGTERM:
stopOnSignal()
gracefulStop(signals, syscall.SIGTERM)
case syscall.SIGINT:
stopOnSignal()
gracefulStop(signals, syscall.SIGINT)
2020-07-26 17:09:05 +08:00
default:
logx.Error("Got unregistered signal:", v)
}
}
}()
}
2021-09-04 12:16:30 +08:00
// Done returns the channel that notifies the process quitting.
func Done() <-chan struct{} {
return done
}
func stopOnSignal() {
select {
case <-done:
// already closed
default:
close(done)
}
}