Middle+
What is a long killer?
sobes.tech AI
Answer from AI
Long Killer is a user script in Unix/Linux systems designed to find and forcibly terminate processes running longer than a specified time. It is commonly used for resource management and preventing system hangs. It can be implemented in various scripting languages such as Bash or Python.
Working principle:
- Determining the list of running processes (e.g., using
ps). - Filtering processes based on various criteria (user, command name, etc.).
- Determining the runtime of each relevant process.
- Comparing the runtime with a predefined threshold.
- Sending a termination signal (e.g.,
SIGTERMorSIGKILL) to processes that exceed the threshold.
Example implementation in Bash:
#!/bin/bash
# Threshold time in seconds
THRESHOLD_SECONDS=3600 # 1 hour
# Name of the process to search for. Leave empty '' to search all processes of the user
PROCESS_NAME=""
# User under whose account the processes are running. Leave empty '' to search processes of all users
USER=""
# Exclude processes by name (space-separated)
EXCLUDE_PROCESSES="sshd bash long_killer.sh"
# Get list of processes, their runtime (ET), PID, command name, and user
ps -eo etime,pid,cmd,user --no-headers | while read ET PID CMD USER_NAME; do
# Convert runtime to seconds
SECS=0
if [[ "$ET" =~ ([0-9]+)-([0-9]+):([0-9]+):([0-9]+) ]]; then # Days-hours:minutes:seconds
SECS=$(( ${BASH_REMATCH[1]}*86400 + ${BASH_REMATCH[2]}*3600 + ${BASH_REMATCH[3]}*60 + ${BASH_REMATCH[4]} ))
elif [[ "$ET" =~ ([0-9]+):([0-9]+):([0-9]+) ]]; then # Hours:minutes:seconds
SECS=$(( ${BASH_REMATCH[1]}*3600 + ${BASH_REMATCH[2]}*60 + ${BASH_REMATCH[3]} ))
elif [[ "$ET" =~ ([0-9]+):([0-9]+) ]]; then # Minutes:seconds
SECS=$(( ${BASH_REMATCH[1]}*60 + ${BASH_REMATCH[2]} ))
elif [[ "$ET" =~ ([0-9]+) ]]; then # Seconds
SECS=${BASH_REMATCH[1]}
fi
# Check conditions for termination
KILL=false
if [ "$SECS" -gt "$THRESHOLD_SECONDS" ]; then
KILL=true
fi
if [ -n "$PROCESS_NAME" ] && [[ ! "$CMD" =~ "$PROCESS_NAME" ]]; then
KILL=false
fi
if [ -n "$USER" ] && [ "$USER_NAME" != "$USER" ]; then
KILL=false
fi
# Check exclusion list
for EXCLUDE in $EXCLUDE_PROCESSES; do
if [[ "$CMD" == *"$EXCLUDE"* ]]; then
KILL=false
break
fi
done
# Terminate process if all conditions are met and it's not the current script
if [ "$KILL" = true ] && [ "$PID" != "$$" ]; then
echo "Killing process $PID ($CMD) running for $ET"
kill $PID # You can use kill -9 $PID for forceful termination
fi
done
This script can be scheduled to run periodically, for example, via Crontab.
# Run every minute
* * * * * /path/to/your/long_killer.sh >> /var/log/long_killer.log 2>&1
It is important to carefully set the criteria and thresholds to avoid unintentional termination of critical system processes.