From 5e54ec629e6055e7aa31b2c1273e203fd35e6951 Mon Sep 17 00:00:00 2001 From: xtaci Date: Thu, 19 Sep 2024 18:32:31 +0800 Subject: [PATCH] fix systemd restart waiting due to signal handling --- std/signal.go | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/std/signal.go b/std/signal.go index 2483f3ab..22f8f0cb 100644 --- a/std/signal.go +++ b/std/signal.go @@ -28,16 +28,23 @@ import ( "log" "os" "os/signal" + "sync" "syscall" + "time" kcp "github.com/xtaci/kcp-go/v5" ) +const ( + EXIT_WAIT = 5 // max seconds to wait before exit +) + func init() { go sigHandler() } func sigHandler() { + var exitOnce sync.Once ch := make(chan os.Signal, 1) signal.Notify(ch, syscall.SIGUSR1, syscall.SIGTERM, syscall.SIGINT) signal.Ignore(syscall.SIGPIPE) @@ -51,6 +58,14 @@ func sigHandler() { postProcess() signal.Stop(ch) syscall.Kill(syscall.Getpid(), syscall.SIGTERM) + + // wait for max EXIT_WAIT seconds before exit + exitOnce.Do(func() { + go func() { + <-time.After(EXIT_WAIT * time.Second) + os.Exit(0) + }() + }) } } }