How to Kill All Linux Processes That Are Older Than a Certain Age

How do you kill all Linux processes that are older than a certain age?

If they just need to be killed:

if [[ "$(uname)" = "Linux" ]];then killall --older-than 1h someprocessname;fi

If you want to see what it's matching

if [[ "$(uname)" = "Linux" ]];then killall -i --older-than 1h someprocessname;fi

The -i flag will prompt you with yes/no for each process match.

Kill all R processes that hang for longer than a minute

You may want to avoid killing processes from another user and try SIGKILL (kill -9) after SIGTERM (kill -15). Here is a script you could execute every minute with a CRON job:

#!/bin/bash

PROCESS="R"
MAXTIME=`date -d '00:01:00' +'%s'`

function killpids()
{
PIDS=`pgrep -u "${USER}" -x "${PROCESS}"`

# Loop over all matching PIDs
for pid in ${PIDS}; do
# Retrieve duration of the process
TIME=`ps -o time:1= -p "${pid}" |
egrep -o "[0-9]{0,2}:?[0-9]{0,2}:[0-9]{2}$"`

# Convert TIME to timestamp
TTIME=`date -d "${TIME}" +'%s'`

# Check if the process should be killed
if [ "${TTIME}" -gt "${MAXTIME}" ]; then
kill ${1} "${pid}"
fi
done
}

# Leave a chance to kill processes properly (SIGTERM)
killpids "-15"
sleep 5

# Now kill remaining processes (SIGKILL)
killpids "-9"

Kill a 10 minute old zombie process in linux bash script

Just like real Zombies, Zombie processes can't be killed - they're already dead.

They will go away when their parent process calls wait() to get their exit code, or when their parent process exits.


Oh, you're not really talking about Zombie processes at all. This bash script should be along the lines of what you're after:

ps -eo uid,pid,lstart |
tail -n+2 |
while read PROC_UID PROC_PID PROC_LSTART; do
SECONDS=$[$(date +%s) - $(date -d"$PROC_LSTART" +%s)]
if [ $PROC_UID -eq 1000 -a $SECONDS -gt 600 ]; then
echo $PROC_PID
fi
done |
xargs kill

That will kill all processes owned by UID 1000 that have been running longer than 10 minutes (600 seconds). You probably want to filter it out to just the PIDs you're interested in - perhaps by parent process ID or similar? Anyway, that should be something to go on.



Related Topics



Leave a reply



Submit