github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zutil/daemon/signal_test.go (about) 1 package daemon 2 3 import ( 4 "context" 5 "os" 6 "testing" 7 "time" 8 9 zls "github.com/sohaha/zlsgo" 10 ) 11 12 func TestSignal(t *testing.T) { 13 tt := zls.NewTest(t) 14 ctx, cancel := context.WithTimeout(context.Background(), time.Second) 15 defer cancel() 16 17 tip := "test" 18 signalChan, _ := SignalChan() 19 now := time.Now() 20 select { 21 case <-ctx.Done(): 22 tip = "timeout" 23 case <-signalChan: 24 tip = "signal" 25 } 26 t.Log(time.Since(now), tip) 27 tt.Equal("timeout", tip) 28 29 ctx, cancel = context.WithTimeout(context.Background(), time.Second) 30 defer cancel() 31 select { 32 case <-ctx.Done(): 33 t.Log("timeout") 34 case k, ok := <-SingleKillSignal(): 35 tip = "kill" 36 t.Log(k, ok) 37 } 38 } 39 40 func TestSingleKillSignal(t *testing.T) { 41 tt := zls.NewTest(t) 42 go func() { 43 time.Sleep(time.Second * 1) 44 process, err := os.FindProcess(os.Getpid()) 45 tt.NoError(err, true) 46 process.Signal(os.Interrupt) 47 }() 48 49 now := time.Now() 50 isKill := <-SingleKillSignal() 51 tt.Log(isKill) 52 tt.EqualTrue(time.Since(now) > time.Second*1) 53 54 ReSingleKillSignal() 55 go func() { 56 time.Sleep(time.Second * 2) 57 process, err := os.FindProcess(os.Getpid()) 58 tt.NoError(err, true) 59 process.Signal(os.Interrupt) 60 }() 61 62 now = time.Now() 63 isKill = <-SingleKillSignal() 64 tt.Log(isKill) 65 tt.EqualTrue(time.Since(now) > time.Second*2) 66 }