Skip to content
Myr

fix: prevent signal goroutine deadlock on shutdown (#1806)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by 陈志谦 · committed by GitHub · parent d5bfd5c · Browse files · 2 files+64 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+64 added−5 removed

  • other:+64 added−5 removed

2 files+64 added−5 removed

added:signals_test.go+57 added
1//go:build !windows23package tea45import (6 "context"7 "os"8 "os/signal"9 "syscall"10 "testing"11 "time"12)1314// TestHandleSignalsReturnsAfterContextCancelDuringPendingSend is a15// regression test for the signal-goroutine deadlock on shutdown: a signal16// arriving while nobody reads p.msgs (the event loop already stopped) must17// not block the handler forever once the program context is canceled.18func TestHandleSignalsReturnsAfterContextCancelDuringPendingSend(t *testing.T) {19 ctx, cancel := context.WithCancel(context.Background())20 defer cancel()2122 // Register our own handler first so the SIGINT can never take down the23 // test process before handleSignals registers its own.24 ours := make(chan os.Signal, 1)25 signal.Notify(ours, syscall.SIGINT)26 defer signal.Stop(ours)2728 p := &Program{29 ctx: ctx,30 msgs: make(chan Msg), // unbuffered, no reader: simulates a stopped event loop31 }3233 done := p.handleSignals()34 time.Sleep(100 * time.Millisecond) // let the handler register its signal.Notify3536 if err := syscall.Kill(os.Getpid(), syscall.SIGINT); err != nil {37 t.Fatalf("failed to send SIGINT: %v", err)38 }39 select {40 case <-ours:41 case <-time.After(5 * time.Second):42 t.Fatal("SIGINT was not delivered")43 }44 // Let the handler consume its copy of the signal and enter the send on45 // p.msgs, where it would block forever before the fix.46 time.Sleep(100 * time.Millisecond)4748 // Canceling the context (what shutdown does) must unblock the handler.49 cancel()5051 select {52 case <-done:53 // The handler returned; shutdown can proceed.54 case <-time.After(5 * time.Second):55 t.Fatal("handleSignals did not return after context cancel: signal goroutine is deadlocked")56 }57}
modified:tea.go+7 added-5 removed
672 unmodified lines
673 return674675 case s := <-sig:676 if atomic.LoadUint32(&p.ignoreSignals) == 0 {677 switch s {678 case syscall.SIGINT:679 p.msgs <- InterruptMsg{}680 default:681 p.msgs <- QuitMsg{}677 var msg Msg = QuitMsg{}678 if s == syscall.SIGINT {679 msg = InterruptMsg{}680 }681 select {682 case p.msgs <- msg:683 case <-p.ctx.Done():684 }685 return686 }687 }688 }
778 unmodified lines