File tree Expand file tree Collapse file tree 1 file changed +32
-20
lines changed Expand file tree Collapse file tree 1 file changed +32
-20
lines changed Original file line number Diff line number Diff line change 1515package sighandle
1616
1717import (
18+ "context"
1819 "os"
1920 "os/signal"
2021)
2122
2223type handler struct {
23- sig []os.Signal
24- f func (os.Signal )
25- c chan os.Signal
26- notified bool
24+ sig []os.Signal
25+ handlerFunc func (os.Signal )
26+ sigChannel chan os.Signal
27+ cancel func ()
2728}
2829
29- func (h * handler ) routine () {
30- h .f (<- h .c )
30+ func (h * handler ) routine (ctx context.Context ) {
31+ select {
32+ case <- ctx .Done ():
33+ // cancel this goroutine
34+ case s := <- h .sigChannel :
35+ h .handlerFunc (s )
36+ }
3137}
3238
33- func (h * handler ) notify () {
34- if h .notified {
35- h .reset ()
36- }
37- h .notified = true
38- h .c = make (chan os.Signal , 1 )
39- go h .routine ()
40- signal .Notify (h .c , h .sig ... )
39+ func (h * handler ) notify (ctx context.Context ) {
40+ go h .routine (ctx )
41+ signal .Notify (h .sigChannel , h .sig ... )
4142}
4243
4344func (h * handler ) reset () {
4445 signal .Reset (h .sig ... )
45- h .notified = false
46+ h .cancel ()
4647}
4748
48- var std = & handler {}
49+ var std * handler
4950
5051func Notify (f func (os.Signal ), sig ... os.Signal ) {
51- std .f = f
52- std .sig = sig
53- std .notify ()
52+ Reset ()
53+
54+ ctx , cancel := context .WithCancel (context .Background ())
55+
56+ std = & handler {
57+ handlerFunc : f ,
58+ sig : sig ,
59+ sigChannel : make (chan os.Signal , 1 ),
60+ cancel : cancel ,
61+ }
62+ std .notify (ctx )
5463}
5564
5665func Reset () {
57- std .reset ()
66+ if std != nil {
67+ std .reset ()
68+ std = nil
69+ }
5870}
You can’t perform that action at this time.
0 commit comments