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
Provenance
Commit
ff51ba4
Tree
ee4db87
Author
陈志谦 <89645338+simpleqt@users.noreply.github.com>
Committer
GitHub <noreply@github.com>
Parent
d5bfd5c
2 files changed+64 added−5 removed
added:signals_test.go+57 added
1+//go:build !windows2+3+package tea4+5+import (6+ "context"7+ "os"8+ "os/signal"9+ "syscall"10+ "testing"11+ "time"12+)13+14+// 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.18+func TestHandleSignalsReturnsAfterContextCancelDuringPendingSend(t *testing.T) {19+ ctx, cancel := context.WithCancel(context.Background())20+ defer cancel()21+22+ // 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)27+28+ p := &Program{29+ ctx: ctx,30+ msgs: make(chan Msg), // unbuffered, no reader: simulates a stopped event loop31+ }32+33+ done := p.handleSignals()34+ time.Sleep(100 * time.Millisecond) // let the handler register its signal.Notify35+36+ 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)47+48+ // Canceling the context (what shutdown does) must unblock the handler.49+ cancel()50+51+ 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 }