Go core
Browse topics

Handling OS signals

Version
1.27
Review
Draft

Summary#

signal.Notify delivers selected signals to a channel. signal.NotifyContext cancels a context when one arrives, which suits shutdown code that already accepts a context.

Syntax#

go
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
defer signal.Stop(signals)

Or use a context.

go
ctx, stop := signal.NotifyContext(parent, os.Interrupt)
defer stop()

Example#

The program sends the interrupt to itself. This works on Unix-like systems; sending os.Interrupt this way is not supported on Windows.

go
package main

import (
	"context"
	"fmt"
	"os"
	"os/signal"
)

func channelInterrupt(self *os.Process) error {
	signals := make(chan os.Signal, 1) // buffered
	signal.Notify(signals, os.Interrupt)
	defer signal.Stop(signals)

	if err := self.Signal(os.Interrupt); err != nil {
		return err
	}
	fmt.Println("received interrupt:", <-signals == os.Interrupt)
	return nil
}

func main() {
	self, err := os.FindProcess(os.Getpid())
	if err != nil {
		fmt.Println(err)
		return
	}
	if err := channelInterrupt(self); err != nil {
		fmt.Println(err)
		return
	}

	ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
	defer stop()
	if err := self.Signal(os.Interrupt); err != nil {
		fmt.Println(err)
		return
	}
	<-ctx.Done()
	fmt.Println("context canceled:", ctx.Err() == context.Canceled)
	fmt.Println("signal-specific cause:", context.Cause(ctx) != ctx.Err())
}

Expected output#

Text
received interrupt: true
context canceled: true
signal-specific cause: true

Common mistakes#

Give a Notify channel a buffer, because the package does not block to deliver a signal and an unready receiver can miss it. SIGKILL and SIGSTOP cannot be caught. Call stop after the first signal to release the registration. A second Ctrl+C can then take its default action if no other registration intercepts it.

Version applicability#

Notify dates back to Go 1.0, and Stop arrived in Go 1.1. NotifyContext requires Go 1.16. The example builds from Go 1.20, when context.Cause was added. The signal-specific cause requires Go 1.26, so the last line prints false on Go 1.20 through 1.25.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0