Standard library / os/signal

os/signal.NotifyContext()

Returns a context canceled by specified signals, parent cancellation or stop. Call stop when finished to release registration. Example intended for Linux/AMD64 with Go 1.23.2 in a disposable working directory; other platforms may differ. Expected stdout: 'true\n'.

Formal Syntax & Structure

go syntaxgo
func NotifyContext(parent context.Context, signals ...os.Signal) (ctx context.Context, stop context.CancelFunc)

Parameters & Attributes

NameTypeDescription
parentcontext.ContextParent context.
signals...os.SignalSignals that trigger cancellation.

Return Value

(ctx context.Context, stop context.CancelFunc)

Returns a context canceled by specified signals, parent cancellation or stop.

Working Example

Example Snippetgo
package main
import (  "context"  "fmt"  "os"  "os/signal"  "syscall"  "time")
func must(e error) {  if e != nil {    panic(e)  }}func main() {  ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGUSR1)  defer stop()  must(syscall.Kill(os.Getpid(), syscall.SIGUSR1))  select {  case <-ctx.Done():    fmt.Println(ctx.Err() == context.Canceled)  case <-time.After(time.Second):    panic("timeout")  }}
Go Reference