Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I need the command to kill processes that have been running since at least 5 minutes for a given process.

I will have to run that command every five minutes or so.

Thanks a million !

(system is Centos5)

share|improve this question

2 Answers 2

up vote 1 down vote accepted

I found the solution on this page: http://www.directadmin.com/forum/showthread.php?t=26179

Make a empty file and call it killlongproc.sh

Copy this:

#!/bin/bash
# This script will kill process which running more than X hours
# egrep: the selected process; grep: hours
PIDS="`ps eaxo bsdtime,pid,comm | egrep "spamd|exim|mysqld|httpd" | grep " 1:" | awk '{print $2}'`"

# Kill the process
echo "Killing spamd, exim, mysqld and httpd processes running more than one hour..."
for i in ${PIDS}; do { echo "Killing $i"; kill -9 $i; }; done;

Stop this in your cronjob

15 * * * * * root /{directory}/./killongproc.sh
share|improve this answer
3  
It's usually a bad idea to do this. What problem are you really trying to solve? Also, you shouldn't use kill -9 since it doesn't give processes a chance to do a graceful cleanup before exiting. –  Dennis Williamson Aug 1 '10 at 14:10
    
This kills processes which consumed some amount of CPU time (user+system), not processes which are running for some amount of real time (e.g. started before 1 hour). –  Marki555 Oct 7 at 9:37

There is a script here that you could modify to do what you want.

EDIT added the script below

#!/bin/bash
#
#Put the UID to kill on the next line
UID_KILL=1001

#Put the time in seconds which the process is allowed to run below
KILL_TIME=300

KILL_LIST=`{
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 $UID_KILL -a $SECONDS -gt $KILL_TIME ]; then
        echo -n "$PROC_PID "
        fi
     done 
}`

if [[ -n $KILL_LIST ]]
then
        kill $KILL_LIST
fi
share|improve this answer
    
I have no enought knowledge to modify it, that's why I'm asking you –  Pierre Aug 1 '10 at 12:52
    
Too complicated. You can use column etimes of ps to show you directly the elapsed seconds since process start (no need to compute it from start time). –  Marki555 Oct 7 at 9:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.