In this tutorial, step-by-step guide to killing Linux processes.
In the day-to-day operation of our web hosting infrastructure, it’s inevitable that some processes may become unresponsive or consume excessive resources. Learning how to locate these processes and terminate them safely is essential for maintaining server performance and reliability. We’ll explore several command-line utilities—such as ps, top, kill, killall, and pkill—to help us identify and manage errant processes on our Linux servers.
Troubleshooting Common kill & pkill Errors
Inspecting Running Processes with ps
The ps (process status) command provides a snapshot of currently running processes. By default, ps shows processes associated with the current shell. To view all processes on the system, we typically combine it with options:
ps aux
a
: Show processes for all usersu
: Display the process’s user/ownerx
: Include processes without a controlling terminal
The columns of interest include:
- USER: Owner of the process
- PID: Process ID, used for targeting commands like kill
- %CPU and %MEM: Resource usage by the process
- COMMAND: Executable name and arguments
Static Snapshot with ps
ps aux | awk '$3 > 50.0 { print }'
- ps aux lists all processes.
- awk ‘$3 > 50.0’ filters by CPU usage >50%.
- Output shows PID, USER, %CPU, %MEM, COMMAND.
Why this matters: Spotting processes hogging CPU or memory pinpoints candidates for termination.
By scanning the output, we can spot processes with unusually high CPU or memory usage. For example, a runaway PHP script might show 100% CPU utilization under the COMMAND column.
Real-Time Monitoring with top and htop
While ps provides a static snapshot, top gives a live, updating view of system processes. Simply running:
top
launches an interactive display, sorted by CPU usage by default. We can press:
- M: Sort by memory usage
- P: Sort by CPU usage
- k: Prompt for a PID to kill
- q: Quit top
For a more user-friendly interface, we often install and use htop:
sudo apt install htop # Debian/Ubuntu
sudo yum install htop # CentOS/RHEL
Execute command:
htop
Within htop, arrow keys allow navigation; pressing F9 brings up a kill menu where a signal (such as SIGTERM or SIGKILL) can be selected.
Graceful Termination with kill
Linux signals let us request process actions:
| Signal | Number | Description |
| -------------- | -------------| ------------------------------------------------------ |
| SIGTERM | 15 | “Please terminate”—graceful exit |
| SIGKILL | 9 | “Force kill”—immediate exit |
| SIGHUP | 1 | Hangup—often reload configuration |
| SIGINT | 2 | Interrupt—like Ctrl+C |
Once the PID of an unresponsive process is known, we can request its termination:
kill <PID>
By default, kill sends the SIGTERM signal (signal number 15), which requests a graceful shutdown, allowing the process to clean up resources. If the process fails to respond, a stronger signal can be used:
kill -9 <PID>
Here, -9 corresponds to SIGKILL, which forces immediate termination without cleanup. We should reserve SIGKILL for stubborn processes, as it may leave temporary files or sockets dangling.
Terminating Processes by Name with killall and pkill
In some scenarios, it’s more convenient to target processes by name rather than by PID:
killall httpd
This command sends SIGTERM to all processes named httpd. To force-kill:
killall -9 httpd
pkill
pkill -f script.php
The -f option matches against the full command line, enabling selection of processes whose names or arguments contain a given pattern. By default, pkill sends SIGTERM, and -9 can be added for SIGKILL.
These commands streamline administration when multiple instances of the same service need to be handled simultaneously.
Checking Signal Definitions
To view all available signals and their numbers, we can reference:
kill -l
This outputs a list of signals (e.g., TERM, KILL, HUP) alongside their numeric codes, ensuring accuracy when scripting automated cleanup routines. Best practice: Always start with SIGTERM (15) to allow cleanup; only escalate to SIGKILL (9) if the process ignores SIGTERM.
| Issue | Symptom | Fix |
| ----------------------------------------------------- | ----------------------------------------- ---------------------| -------------------------------------------------------------------------------------------- |
| **Permission denied** | “Operation not permitted” on `kill <PID>` | Prepend `sudo`, or verify process ownership with `ps -fp PID` |
| **Zombie processes** | STAT column shows “Z” in `ps` | Find parent PID (PPID) and restart parent service |
| **Process respawns immediately** | Process reappears after kill | Stop the supervising service (`systemctl stop …`) before kill |
| **Wrong PID by typo** | Critical service unexpectedly halts | Double-check with `ps -fp PID` before issuing `kill` |
Troubleshooting Recipes
Recipe A: PHP-FPM Hang
ps aux | grep php-fpm
Note PIDs with high CPU.
kill PID1 PID2 … # SIGTERM first
sleep 3
kill -9 PID1 PID2 … # if still running
systemctl reload php-fpm
Recipe B: Zombie Reaping
ps -eo pid,ppid,stat,cmd | grep ' Z '
Identify PPID (parent PID).
systemctl restart <parent-service>
Automating Safety Nets
Place this in root’s crontab (sudo crontab -e) to auto-kill any PHP process older than 1 hour:
0 * * * * /usr/local/bin/cleanup_php.sh
Contents of cleanup_php.sh:
#!/bin/bash
threshold=3600
ps -eo pid,etimes,cmd | grep php-fpm | while read pid etime cmd; do
if [ "$etime" -gt "$threshold" ]; then
kill -15 $pid && sleep 2 && kill -9 $pid
echo "$(date): Terminated $cmd (PID $pid)" >> /var/log/process_cleanup.log
fi
done
Safety tip: Always log automated kills for post-mortem analysis.
Automating Unresponsive Process Cleanup
For critical services prone to hanging—such as long-running backups or batch scripts—we can incorporate monitoring scripts in cron to detect and terminate freezes automatically. A simple Bash snippet might:
- Run ps aux and grep for the target process.
- Check CPU time or elapsed time against a threshold.
- Issue kill if the threshold is exceeded.
However, caution is paramount: automated termination policies should be tested thoroughly to avoid unintended service disruptions.
Best Practices for Safe Process Management
Identify Before Killing: Always confirm the PID and resource usage before terminating a process to prevent accidental shutdown of critical services.
Prefer Graceful Signals: Use SIGTERM initially to allow cleanup routines; reserve SIGKILL for unresponsive cases.
Log Actions: Maintain an audit of terminated processes, including timestamps and reasons, for troubleshooting and accountability.
Monitor Regularly: Implement proactive monitoring with tools like Nagios, Zabbix, or built-in scripts to detect anomalies early.
Document Procedures: Keep standard operating procedures readily accessible to all team members, ensuring consistency in response to process issues.
By mastering these command-line techniques, we strengthen our ability to maintain healthy, responsive servers. Consistent monitoring and thoughtful termination practices help us deliver reliable web hosting services and uphold the performance standards our clients expect.
Check out robust instant dedicated servers, Instant KVM VPS, premium shared hosting and data center services in New Zealand