Skip to content
Myr

signals_test.go

This file

Path

signals_test.go

57 lines · 1.6 KiB · Go

Last changed by

fix: prevent signal goroutine deadlock on shutdown (#1806)陈志谦before adoptionff51ba4

History of this file

Take it

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}