Documentation
¶
Overview ¶
Package ctxsignal can be used to create contexts cancelable by system signals.
You can send a signal using kill -SIGNAL PID (e.g., kill -SIGHUP 170).
kill -l gives you a list of signals available on your system. On Unix-like systems you can use "man signal" to learn about signals. SIGKILL and SIGSTOP signals cannot be intercepted or handled.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Closed ¶
Closed gets the signal that closed a context channel.
Example ¶
package main
import (
"context"
"fmt"
"os"
"syscall"
"github.com/henvic/ctxsignal"
)
func main() {
ctx, cancel := ctxsignal.WithSignals(context.Background(), syscall.SIGHUP)
defer cancel()
// Remove this Go routine to test manually with kill -HUP PID.
go func() {
p, _ := os.FindProcess(os.Getpid()) // always check your errors!
_ = p.Signal(syscall.SIGHUP) // don't ignore errors!
}()
<-ctx.Done()
sig, err := ctxsignal.Closed(ctx)
if err != nil {
_, _ = fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
fmt.Println(sig)
}
Output: hangup
func WithSignals ¶
func WithSignals(parent context.Context, signals ...os.Signal) (context.Context, context.CancelFunc)
WithSignals returns a copy of the parent context cancelable by the given system signals. The signals are reset when the context's Done channel is closed.
Example ¶
package main
import (
"context"
"fmt"
"os"
"syscall"
"github.com/henvic/ctxsignal"
)
func main() {
ctx, cancel := ctxsignal.WithSignals(context.Background(), syscall.SIGUSR2)
defer cancel()
// Remove this Go routine to test manually with kill -USR2 PID.
go func() {
p, _ := os.FindProcess(os.Getpid()) // always check your errors!
_ = p.Signal(syscall.SIGUSR2) // don't ignore errors!
}()
<-ctx.Done()
fmt.Println("Signaled!")
}
Output: Signaled!
func WithTermination ¶
WithTermination creates a context canceled on signals SIGINT or SIGTERM.
Example ¶
package main
import (
"context"
"fmt"
"os"
"syscall"
"github.com/henvic/ctxsignal"
)
func main() {
ctx, cancel := ctxsignal.WithTermination(context.Background())
defer cancel()
// Remove this Go routine to test manually.
go func() {
p, _ := os.FindProcess(os.Getpid()) // always check your errors!
_ = p.Signal(syscall.SIGINT) // don't ignore errors!
}()
<-ctx.Done()
fmt.Println("Interrupted!")
}
Output: Interrupted!
Types ¶
This section is empty.
Notes ¶
Bugs ¶
Be aware signal handling is vulnerable to race conditions.
Source Files
¶
- ctxsignal.go