The kill
command is a powerful tool for terminating running processes in a Linux system. It provides a flexible way to send signals to processes, allowing you to gracefully stop, forcefully kill, or perform other actions on them.
Basic Syntax
kill [options] pid(s)
Common Signals
-1
(SIGHUP): Hang up-2
(SIGINT): Interrupt-3
(SIGQUIT): Quit-9
(SIGKILL): Terminate (force)-15
(SIGTERM): Terminate (graceful)-19
(SIGSTOP): Stop-20
(SIGTSTP): Terminal stop
Real-World Examples
1. Terminate a Process
# Terminate a process by PID
$ kill 1234
# Terminate a process by name
$ pkill nginx
2. Use Specific Signals
# Send SIGINT (Ctrl+C) to a process
$ kill -2 1234
# Force terminate a process (SIGKILL)
$ kill -9 1234
3. Terminate All Processes for a User
# Kill all processes owned by a user
$ pkill -u username
Common Use Cases
-
Process Management
# Terminate a hung process $ kill -9 1234 # Gracefully stop a service $ kill -15 $(pidof nginx)
-
Troubleshooting
# Stop a process for debugging $ kill -19 1234 # Resume a stopped process $ kill -18 1234
-
Automation and Scripting
# Kill processes older than 1 hour $ ps -eo pid,etime | awk '$2 > "01:00:00" { print $1 }' | xargs kill -9
Tips and Tricks
-
Use Process Names
# Terminate all instances of a process $ pkill nginx
-
Combine with Other Commands
# Kill top CPU-consuming process $ kill -9 $(ps -eo pid,%cpu,comm | sort -k 2 -r | head -1 | awk '{print $1}')
-
Graceful Termination
# Send SIGTERM first, then SIGKILL $ kill 1234 $ sleep 5 $ kill -9 1234
Best Practices
-
Verify Process Existence
# Check if process is still running $ ps -p 1234
-
Use Appropriate Signals
# Use SIGTERM for graceful termination $ kill -15 1234
-
Automate Process Monitoring
# Restart a service if it crashes $ while true; do ps -C nginx || /etc/init.d/nginx restart sleep 60 done
Common Errors and Solutions
-
Permission Denied
# Use sudo for restricted processes $ sudo kill 1234
-
Process Not Found
# Verify process ID $ ps -p 1234
-
Signal Not Recognized
# Use valid signal names or numbers $ kill -TERM 1234 $ kill -15 1234
Related Commands
ps
: Process statustop
: Interactive process monitoringhtop
: Enhanced process viewerpgrep
: Find processes by namepkill
: Kill processes by name
Advanced Usage
1. Scripting with kill
#!/bin/bash
# Kill processes using excessive CPU
for pid in $(ps -eo pid,%cpu --sort=-%cpu | awk '/[0-9]+/ {if ($2 > 50) print $1}'); do
echo "Killing