Understanding Linux Signals, kill Command, and trap Command
This article explains the types and default actions of Linux signals, distinguishes between standard and real‑time signals, and demonstrates how to use the kill and trap commands with practical shell script examples for signal handling.
1. Linux Signal Types
Signals are software‑level simulations of hardware interrupts; sending a signal to a process triggers a corresponding handler.
Processes can respond to a signal by ignoring it (except SIGKILL and SIGSTOP, which cannot be ignored), catching it with a custom handler, or performing the default action defined by the kernel.
The way a signal is handled depends on the API function used to deliver it.
Linux defines many signals; the most common ones are highlighted in the table below.
Number
Signal Name
Default Action
Description
1
SIGHUP
Terminate
Terminate process, hang up
2
SIGINT
Terminate
Keyboard interrupt (Ctrl+C)
3
SIGQUIT
CoreDump
Keyboard quit (Ctrl+\)
9
SIGKILL
Terminate
Immediately stop process; cannot be caught or ignored
15
SIGTERM
Terminate
Graceful termination; can be caught
additional rows omitted for brevity
CoreDump means the kernel writes a core file for debugging when a process aborts unexpectedly.
Linux supports two categories of signals:
Standard signals (1‑31) are non‑real‑time, not queued, and may be lost if sent repeatedly.
Extended (real‑time) signals (32‑64) are reliable and queued, preserving the number of occurrences.
Understanding a few common signals is sufficient for most tasks.
2. kill Command
The kill command sends signals to processes.
Syntax:
kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... kill -l [sigspec]Options:
-s – specify signal name
-n – specify signal number
-l – list signal names
Example:
# Send termination signal to a process
kill -s SIGTERM pid
# or using number
kill -n 15 pid
# or short form
kill -15 pid3. trap Command
The trap command defines how a shell script should react to received signals.
Syntax:
trap [-lp] [[arg] signal_spec ...]Common actions after catching a signal:
Remove temporary files
Ignore the signal
Prompt the user before terminating the script
Examples:
#!/bin/bash
trap "" 2 # Ignore SIGINT (Ctrl+C)
for i in {1..10}; do
echo $i
sleep 1
done #!/bin/bash
trap "echo 'exit...'; exit" 2
for i in {1..10}; do
echo $i
sleep 1
done #!/bin/bash
trap "func" 2
func() {
read -p "Terminate the process? (Y/N): " input
if [ "$input" == "Y" ]; then
exit
fi
}
for i in {1..10}; do
echo $i
sleep 1
doneThese examples show how to ignore, handle, or prompt the user when a signal like SIGINT is received.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.