Signal Handling Techniques
Understanding Signals
Signal Basics
Signals are software interrupts sent to a program to indicate a specific event or request.
Common Signals
Signal |
Number |
Description |
SIGINT |
2 |
Interrupt from keyboard (Ctrl+C) |
SIGTERM |
15 |
Termination signal |
SIGKILL |
9 |
Immediate process termination |
SIGSTOP |
19 |
Pause process execution |
Signal Flow Diagram
stateDiagram-v2
[*] --> Normal_Execution
Normal_Execution --> Signal_Received: Process gets signal
Signal_Received --> Signal_Handled: Default/Custom Handler
Signal_Handled --> Normal_Execution
Signal_Handled --> Process_Terminated: If fatal signal
Signal Handling in C Programming
Basic Signal Handling Example
#include <signal.h>
#include <stdio.h>
void signal_handler(int signum) {
if (signum == SIGINT) {
printf("Caught SIGINT! Cleaning up...\n");
// Perform cleanup operations
exit(signum);
}
}
int main() {
// Register signal handler
signal(SIGINT, signal_handler);
while(1) {
// Continuous process
sleep(1);
}
return 0;
}
Advanced Signal Handling
Sigaction Approach
#include <signal.h>
struct sigaction sa;
sa.sa_handler = custom_handler;
sa.sa_flags = SA_RESTART;
sigaction(SIGTERM, &sa, NULL);
Signal Handling Best Practices
- Always have a signal handler for critical signals
- Minimize work done in signal handlers
- Use async-signal-safe functions
- Handle potential race conditions
Blocking and Unblocking Signals
## Block specific signals
kill -STOP PID
## Unblock signals
kill -CONT PID
Tool |
Purpose |
kill |
Send signals to processes |
killall |
Send signals to processes by name |
pkill |
Signal processes based on name/attributes |
LabEx Insight
In LabEx's Linux environments, you can experiment with signal handling techniques safely and interactively.
Common Signal Handling Patterns
Graceful Shutdown
void handle_shutdown(int signum) {
// Perform cleanup
// Close resources
// Log shutdown reason
exit(0);
}
Ignore Specific Signals
signal(SIGINT, SIG_IGN); // Ignore interrupt signal
Error Handling and Logging
- Always log signal events
- Implement robust error recovery
- Avoid blocking in signal handlers