Skip to content

Commit

Permalink
⚙️ refactor: Signal handling in daemon
Browse files Browse the repository at this point in the history
  • Loading branch information
sohaha committed Apr 13, 2024
1 parent 9e49a7f commit 268979a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
24 changes: 16 additions & 8 deletions zutil/daemon/signal.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down
5 changes: 4 additions & 1 deletion zutil/daemon/signal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,18 @@ 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())
tt.NoError(err, true)
process.Signal(os.Interrupt)
}()

now = time.Now()
now := time.Now()
<-SingleKillSignal()
tt.EqualTrue(time.Since(now) > time.Second*1)

Expand Down

0 comments on commit 268979a

Please sign in to comment.