Skip to content

Latest commit

 

History

History
56 lines (33 loc) · 1.8 KB

File metadata and controls

56 lines (33 loc) · 1.8 KB

Linux Signal Handling

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.

Common Signals:

  • 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.

Signal Handling in Bash:

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.

Common Signal Use Cases:

  1. Graceful Shutdown:

    • Use SIGTERM to gracefully shut down a process, allowing it to clean up before termination.
  2. Restart or Reload:

    • Use SIGHUP to signal a process to reload its configuration.
  3. Ctrl+C Handling:

    • Use SIGINT to capture the Ctrl+C interrupt and handle it appropriately.
  4. Error Handling:

    • Use custom signals for error handling within your application.

Conclusion:

Understanding and implementing signal handling is crucial for creating robust and responsive Linux applications, allowing them to gracefully handle various events and user interactions.