How to Find and Kill Processes in Linux: A Practical Guide

0saves

Managing processes efficiently is a fundamental skill for any Linux user. There are instances, such as when an application becomes unresponsive or is consuming too much memory, where terminating processes becomes necessary. This post builds on the basics covered in a previous article, “Monitoring Processes in Linux with the ps Command: checking web server Apache processes information“, and dives into how to find and terminate specific processes, using `httpd` processes as our example.

Finding `httpd` Processes

To list all active `httpd` processes, use the command:

ps aux | grep -v grep | grep "httpd"

This command filters the list of all running processes to only show those related to `httpd`. The `grep -v grep` part excludes the grep command itself from the results.

Understanding the Output

The output columns USER, PID, %CPU, and others provide detailed information about each process, including its ID (PID) which is crucial for process management.

Killing Processes Manually

To terminate a process, you can use the `kill` command followed by the process ID (PID):

kill -s 9 29708 29707 ...

Here, `-s 9` specifies the SIGKILL signal, forcing the processes to stop immediately. It’s important to use SIGKILL cautiously, as it does not allow the application to perform any cleanup operations.

Automating with a Script

For convenience, you can automate this task with a simple shell script:

#!/bin/bash

# Find PIDs of httpd processes
OLD_HTTPD_PIDS=$(ps aux | grep "httpd" | grep -v "grep" | awk '{print $2}')

# Loop through and kill each process
for FPID in ${OLD_HTTPD_PIDS}; do
  echo "Killing httpd process pid: ${FPID}"
  kill -s 9 ${FPID}
done

After saving the script as `/root/bin/kill_httpd.sh`, make it executable:

chmod -v 755 /root/bin/kill_httpd.sh

And run it:

/root/bin/kill_httpd.sh

Final Thoughts

Proper process management ensures the smooth operation of Linux systems. While SIGKILL is effective for unresponsive processes, understanding different signals and their effects allows for more nuanced control. Always proceed with caution, especially when terminating processes, to avoid unintended system behavior or data loss.