Friday, June 7, 2013

Check Percentage of CPU usage - Linux

Hi folk,

A couple of days ago, I did not know that one of my CPU was running at 100% capacity because a process was "hung".





So, I had to make a Kill -9, but to my surprise, the next day I had the same problem.

Once I solved the problem I kept thinking, how many times did this happen with other process on my laptop and I have not noticed?

To stay informed I have created the following bash script to check the top 10 processes.

#!/bin/sh
# Check Percentage of CPU usage
# Jorge Iglesias

# Skip first lines from top command with head -17
# PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
# Select top ten proccess with -n 10
top -n1 -b | head -17 | tail -n 10 > top.txt

while read line
do
    ind=0
    pid=""

    for line in $line;
    do
        if [ $ind -eq 0 ]    # index of PID
        then
            pid=$line
          
        fi

        if [ $ind -eq 8 ]    # index of %CPU
        then
            min=80.0     # min value alert
            if [ 1 -eq `echo "${line} > ${min}" | bc` ]
            then
                notify-send -t 5000 -i error "Percentage of CPU usage" "The %CPU usage for process <b>id $pid</b> is <b>$line%</b> \n\nPlease review and kill the process."      
            fi
            break;         # break line, only read to %CPU value
        fi
        ((ind+=1))
    done
done < top.txt

rm top.txt                # delete temp file


I scheduled the script to run every 10 minutes and when it detects that a process up to 80% then is reported on screen.

 
You can watch the process using the top command.


Now, you decide if you really want to "kill" the process or not :-)

I hope this helps!!

Cheers.

No comments:

Post a Comment