From 268979adf6503375467307fb70ef29ac04c59f81 Mon Sep 17 00:00:00 2001 From: seekwe Date: Sat, 13 Apr 2024 12:46:58 +0800 Subject: [PATCH] =?UTF-8?q?=E2=9A=99=EF=B8=8F=20refactor:=20Signal=20handl?= =?UTF-8?q?ing=20in=20daemon?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- zutil/daemon/signal.go | 24 ++++++++++++++++-------- zutil/daemon/signal_test.go | 5 ++++- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/zutil/daemon/signal.go b/zutil/daemon/signal.go index c7abca9..7394b8a 100644 --- a/zutil/daemon/signal.go +++ b/zutil/daemon/signal.go @@ -2,41 +2,49 @@ package daemon import ( "sync" - - "github.com/sohaha/zlsgo/zutil" ) var ( singleSignal sync.Once - single = make(chan bool) - singleNum = zutil.NewInt32(0) + single = make(chan bool) + singleNum uint = 0 + singleLock sync.Mutex ) func singelDo() { singleSignal.Do(func() { go func() { kill := KillSignal() + singleLock.Lock() for { - if int(singleNum.Sub(1)) < 0 { - singleNum.Add(1) + if singleNum == 0 { break } + + singleNum-- single <- kill } close(single) + singleLock.Unlock() }() }) } func SingleKillSignal() <-chan bool { - singleNum.Add(1) + singleLock.Lock() + defer singleLock.Unlock() + + singleNum++ singelDo() return single } func ReSingleKillSignal() { - if singleNum.Load() > 0 { + singleLock.Lock() + defer singleLock.Unlock() + + if singleNum > 0 { return } diff --git a/zutil/daemon/signal_test.go b/zutil/daemon/signal_test.go index 76f52f6..66bbbfc 100644 --- a/zutil/daemon/signal_test.go +++ b/zutil/daemon/signal_test.go @@ -35,7 +35,10 @@ func TestSignal(t *testing.T) { tip = "kill" t.Log(k, ok) } +} +func TestSingleKillSignal(t *testing.T) { + tt := zls.NewTest(t) go func() { time.Sleep(time.Second * 1) process, err := os.FindProcess(os.Getpid()) @@ -43,7 +46,7 @@ func TestSignal(t *testing.T) { process.Signal(os.Interrupt) }() - now = time.Now() + now := time.Now() <-SingleKillSignal() tt.EqualTrue(time.Since(now) > time.Second*1)