Package ctxsignal can be used to create contexts cancelable by system signals.
Creating a context copy cancelable when intercepting a SIGINT, SIGTERM, or SIGHUP signal:
ctx, cancel := ctxsignal.WithSignals(context.Background(), syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
defer cancel()
<-ctx.Done()
fmt.Println("Received signal!")
You can check what type of signal was received with:
sig, err := ctxsignal.Closed(ctx)
if err != nil {
return err
}
fmt.Println(sig) // sig type is os.Signal
You can send a signal using kill -SIGNAL PID
. Example: kill -SIGHUP 170
.
On Unix-like systems you can read the manual about signals with
$ man signal
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGPOLL 30) SIGPWR 31) SIGSYS 32) SIGRTMIN
64) SIGRTMAX
SIGKILL and SIGSTOP signals cannot be intercepted or handled.
See the docs for more examples and information.