Automatically killing processes that use too much memory


Every other week or so, I run some sort of code on my workstation that uses more memory than I expect. If I'm lucky, I notice the swap space graph climbing in my taskbar's monitor, and quickly find and kill the process. If I'm not so lucky, it keeps consuming memory until my workstation is effectively frozen.

These processes are never system-critical, so I put together a little script that will find these jobs and kill them before they become a problem.

1) Drop this in a file of your choosing, replacing my username and paths with your own_

ps -o %mem,pid,comm,args -U cmiller | perl -ane 'if($F[0] > 80.0){print $F[1] . "\n";}' | while read i;do echo "$(date): Killing $_" >>/home/cmiller/logs/killbigmem.log;kill $i;done

It's using ps to grab processes, then looking for those that are using more than 80% of the system memory. This may or may not be the threshold that you want to use. Also note that it also logs the process it just killed, so you can figure out where your job went later.

2) Make the file executable_

chmod +x killbigmem.sh

3) Put the process in your cron so it runs every minute. Run crontab -e, then insert the following line (again, replacing paths as necessary).

*/1 * * * * /gscuser/cmiller/usr/bin/killbigmem.sh

Comments

comments powered by Disqus