In Linux, signals are software interrupts that notify a process that a specific event has occurred. Signal handling allows processes to respond to these events, such as errors or user-defined conditions. Each signal is identified by a unique integer number, and it has a predefined meaning.
- SIGTERM (15): Termination signal. This is a gentle request for a process to terminate.
- SIGKILL (9): Kill signal. This forcefully terminates a process.
- SIGHUP (1): Hangup signal. Often used to reload configuration files.
- SIGINT (2): Interrupt signal. Generated when the user presses Ctrl+C.
In a Bash script, you can use the trap
command to set up signal handlers.
#!/bin/bash
function handle_signal() {
echo "Received signal"
# Handle the signal here
}
trap 'handle_signal' SIGINT SIGTERM
# Rest of the script
# ...
trap 'handler' signals
: Sets up a trap to catch the specified signals and execute the given handler.
-
Graceful Shutdown:
- Use SIGTERM to gracefully shut down a process, allowing it to clean up before termination.
-
Restart or Reload:
- Use SIGHUP to signal a process to reload its configuration.
-
Ctrl+C Handling:
- Use SIGINT to capture the Ctrl+C interrupt and handle it appropriately.
-
Error Handling:
- Use custom signals for error handling within your application.
Understanding and implementing signal handling is crucial for creating robust and responsive Linux applications, allowing them to gracefully handle various events and user interactions.