Process Killer Bash Script to Terminate Rogue Processes

marius

Administrator
Staff member
Introduction:
This bash script monitors and terminates processes consuming excessive resources. It identifies processes by their names and terminates them if they exceed a certain threshold.

Bash:
#!/bin/bash

# Process name to monitor
PROCESS_NAME="some_process"

# Get process ID and CPU usage
pid=$(pgrep -f $PROCESS_NAME)

if [ -z "$pid" ]; then
    echo "Process $PROCESS_NAME not found."
else
    cpu_usage=$(ps -p $pid -o %cpu --no-headers | awk '{print int($1)}')
    echo "CPU usage of $PROCESS_NAME: $cpu_usage%"
    if [ $cpu_usage -gt 50 ]; then
        kill -9 $pid
        echo "Process $PROCESS_NAME killed due to high CPU usage."
    else
        echo "Process $PROCESS_NAME is within normal limits."
    fi
fi

Instructions:
Run the script using these commands:
Code:
chmod +x process_killer.sh
./process_killer.sh

Example Output:
Code:
CPU usage of some_process: 65%
Process some_process killed due to high CPU usage.
 
Back
Top