Cleaning up my ‘dump’ directory, I found this aging script I got from somewhere, which will check the current CPU usage of a program and kill it if it uses too much. This is useful if you are for some reason forced to run buggy, closed source software which get stuck in endless loops when things go wrong. I’ve been there, it wasn’t fun, but this thing solved it. Thank you, french christmas…
#!/bin/bash # March-13-2006 # CPUuse trigger script by Noel # # bash code to watch a running program's CPU usage. # if it's above a set value, it will auto send an email. # You will need to set a Cron job to run this script every xx minutes # # Set some needed things: # processToWatch="convert" # in my case I need to watch convert emailAddress="root@host" # this is my main emailaddress triggerValue=90 # if the CPU use is above 90% send an email. DO NOT USE a DOT or COMMA! tempFileName=tmp-cpu # some name of the temp file for the ps, grep data ps auxww | grep "$processToWatch" | grep -v grep > /tmp/$tempFileName export LINE ( read LINE while [ -n "$LINE" ] do set $LINE read LINE if [ $(echo "$3" | sed -e 's/\.[0-9]*//g') -gt $triggerValue ]; then mail -s "CPU message alert for: $processToWatch" $emailAddress <<-END This is to inform you that the following process: $processToWatch with PID (Process ID) $2 is now using more than your preset $triggerValue value. Process: $processToWatch is using: $3 of CPU power! The command used is: $11 END fi done )< /tmp/$tempFileName
8 Comments
FANTASTIC! this is perfect to kill rogue processes when my students screw up
Hi,
I get this error.
/root/apache-cpu-checker.sh: line 35: syntax error: unexpected end of file
Any ideas?
Hey 🙂
The problem was the indentation what was added by one of the editors I use.
This line:
mail -s “CPU message alert for: $processToWatch” $emailAddress <<-END ..reads until it finds "END" on its own, as a line. Having that line indented to look "nice" doesn't work. The script will not find it and thus unexpectedly find the end of the file further down. I removed the indentation in the post. Hope it helps, and thanks for pointing that out 🙂
Will it work on FreeBSD?
It might. Why not try it and let me know how it goes? 🙂
I don’t run FreeBSD myself.
Yeah. Tried it and it works fine. Thanks 🙂
hi bolt!
I’m a newbie, i found your post and i tried to edit it :
—–
processToWatch=”convert”
emailAddress=”agc.prototype@gmail.com”
triggerValue=90
tempFileName=tmp-cpu
ps auxww | grep “$processToWatch” | grep -v grep > /tmp/$tempFileName
export LINE
(
read LINE
while [ -n “$LINE” ]
do
set $LINE
read LINE
if [ $(echo “$3” | sed -e ‘s/\.[0-9]*//g’) -gt $triggerValue ];
then
mail -s “CPU message alert for: $processToWatch” $emailAddress
fi
done
)< /tmp/$tempFileName
……..
Is it ok?
Just try it. Set a low trigger value and see what happens 🙂