How to kill a process that has run too long and takes too much memory in linux using cron, ps and grep
Ranked #5,646 in Tech & Geek, #129,757 overall
Killing runaway processes in linux
This is a simple guide for setting up a cron job that will kill a linux process that has run away. On my web server I occasionally have a process called getsite.php that runs for too long, and takes up lots of memory.
The process
First add the following line to cron using crontab -e. (Crontab defaults to using the vi editor, so if you want to change it first run export VISUAL="nano -w", or your favorite editor.)
Here is the line:
10 * * * * username ps -o sz,etime,pid,comm,args -U username | grep scriptname.php | grep -v grep | perl -ane '($m,$s) = split /:/,$F[1]; $kb=$F[0]; $pid = $F[2]; if(($m>3)&&($kb>10000)) {print "$m :: $s $kb $pid\n"; kill 9, $pid;}'
This should be taylored for the script you want to kill. The breakdown is below.
Here is the line:
10 * * * * username ps -o sz,etime,pid,comm,args -U username | grep scriptname.php | grep -v grep | perl -ane '($m,$s) = split /:/,$F[1]; $kb=$F[0]; $pid = $F[2]; if(($m>3)&&($kb>10000)) {print "$m :: $s $kb $pid\n"; kill 9, $pid;}'
This should be taylored for the script you want to kill. The breakdown is below.
The breakdown
To modify the script for your use you need to do the following:
1. update username to your linux account.
2. update scriptname.php to name of the script that occasionally runs away on you.
3. Currently the script will only kill process over 3 minute of run time, and 10000 kb of memory. You can change these numbers how you like.
4. The script will run every 10 minutes. If you want to change this time, the 10 in front can be changed.
1. update username to your linux account.
2. update scriptname.php to name of the script that occasionally runs away on you.
3. Currently the script will only kill process over 3 minute of run time, and 10000 kb of memory. You can change these numbers how you like.
4. The script will run every 10 minutes. If you want to change this time, the 10 in front can be changed.
How does it work?
Basically the script uses ps to list processes, and then uses grep to strip out only processes that ran the particular script. Then the output is sent to perl. There is a whole perl program included on the one line that checks if processes have used too much memory and have run too long. The script is more clear if broken into multiple lines:
($m,$s) = split /:/,$F[1];
$kb=$F[0]; $pid = $F[2];
if(($m>3)&&($kb>10000))
{print "$m :: $s $kb $pid\n";
kill 9, $pid;}
($m,$s) = split /:/,$F[1];
$kb=$F[0]; $pid = $F[2];
if(($m>3)&&($kb>10000))
{print "$m :: $s $kb $pid\n";
kill 9, $pid;}
by jstonedotorg
A Guy who apparently has some time on his hands (to make websites). (more)



