What are Unix signals?Signals are software interrupts that provide a way to handle asynchronous events. Common signals include SIGINT (Ctrl+C), SIGTERM (termination request), and SIGKILL (forced termination).Learn more about Unix signals on Wikipedia.
Modern Signal Handling with Contexts
Go provides a modern, context-based approach to signal handling through thesignal.NotifyContext function.
How It Works
Create signal-aware context
signal.NotifyContext returns a context that automatically cancels when any of the specified signals are received.Common Signals
SIGINT
Interrupt signal - Sent when user presses Ctrl+CUse for: Graceful shutdown of interactive programs
SIGTERM
Termination signal - Polite request to terminateUse for: Clean shutdown with resource cleanup
SIGKILL
Kill signal - Cannot be caught or ignoredUse for: Force termination (you can’t handle this in Go)
SIGHUP
Hangup signal - Terminal disconnectionUse for: Reload configuration without restarting
Example: Graceful Server Shutdown
Here’s a practical example of using signals for graceful server shutdown:This pattern ensures that in-flight requests complete before the server shuts down, preventing data loss or corrupted responses.
Running the Example
When you run the basic signals program:^C is displayed by your terminal when you press Ctrl+C.
Context Cause
Thecontext.Cause function tells you why the context was canceled:
Why use contexts for signals?
Why use contexts for signals?
Context-based signal handling provides several benefits:
- Composability: Easily integrate with other context-aware code
- Cancellation propagation: Signal cancellation flows through your entire call stack
- Resource cleanup: Automatic cleanup with
defer stop() - Modern idiom: Aligns with Go’s context-based patterns
What about signal.Notify?
What about signal.Notify?
The older
signal.Notify API still works but requires manual channel management:signal.NotifyContext is generally preferred for new code because it integrates better with context-based APIs.Can I handle multiple signals differently?
Can I handle multiple signals differently?
Yes! Check the signal type after receiving:
Best Practices
Always defer stop()
Clean up signal handler resources to prevent leaks
Set shutdown timeouts
Give cleanup a time limit to prevent hanging
Handle SIGINT and SIGTERM
These are the most common graceful shutdown signals
Log signal reception
Help with debugging and monitoring
Related Topics
Exit
Control program exit status codes
Logging
Log signal events and shutdown processes