DB / Linux Kernel/Shell / SIGINT (Signal 2)
INFO

Linux Kernel/Shell Interrupt Signal

SIGINT (Signal Interrupt) is a signal sent to a process to request its termination. It is typically initiated by the user pressing Ctrl+C in a terminal, but can also be sent programmatically. Processes can catch and handle this signal to perform cleanup before exiting, or they can ignore it.

Common Causes

  • User pressing Ctrl+C in the terminal where the process is running.
  • Another process sending SIGINT using `kill -2 <pid>` or `kill -SIGINT <pid>`.
  • A script or program explicitly sending the signal to a child process.

How to Fix

1 Handle SIGINT in Scripts for Graceful Exit

Implement signal handlers in shell scripts or applications to catch SIGINT, perform necessary cleanup (e.g., releasing resources, saving state), and then exit gracefully. This prevents abrupt termination and potential data corruption.

BASH
$ #!/bin/bash function cleanup { echo "Caught SIGINT. Performing cleanup..." # Add your cleanup commands here, e.g., # rm -f /tmp/mylockfile # killall mychildprocess echo "Cleanup complete. Exiting." exit 0 } # Trap SIGINT (Signal 2) trap cleanup SIGINT echo "Process started. Press Ctrl+C to send SIGINT." while true; do echo "Working..." sleep 1 done

2 Ignore SIGINT (Use with Caution)

For specific scenarios where a process should not be interrupted by Ctrl+C (e.g., critical background tasks or daemons), you can configure it to ignore SIGINT. Use with caution, as this can make processes harder to stop without using `kill -9`.

BASH
$ #!/bin/bash # Ignore SIGINT trap '' SIGINT echo "Process started. SIGINT will be ignored. Use kill -9 <pid> to stop." while true; do echo "Working, ignoring Ctrl+C..." sleep 1 done

3 Send SIGINT to a Process Programmatically

If you need to programmatically send a SIGINT signal to a running process (e.g., from another script or for testing purposes), use the `kill` command with the signal number or name.

BASH
$ # Find the PID of the process (replace 'my_process' with actual name or PID) PID=$(pgrep my_process_name) if [ -n "$PID" ]; then echo "Sending SIGINT to process $PID" kill -SIGINT $PID # or kill -2 $PID else echo "Process 'my_process_name' not found." fi