A bash script to get the CPU usage by process
usage:
nohup ./check_proc bwengine 70 &
bwegnine is the process name we want to monitor
70 is to log only when the process is using over 70% of the CPU.
Check the logs at:
/var/log/check_procs.log the output shoul be like
DATE | TOTAL CPU | CPU USAGE | Process details
03/12/14 17:11 |20.99|98| ProdPROXY-ProdProxyPA.tra
03/12/14 17:11 |20.99|100| ProdPROXY-ProdProxyPA.tra
03/12/14 17:11 |20.99|134| ProdPROXY-ProdProxyPA.tra
Here is the code:

#!/bin/bash
# 1: ['command\ name' or PID number(,s)] 2: MAX_CPU_PERCENT
# Script to monitor Process CPU usage
# Original by Erik Lundmark
# Updated By Felipe Ferreira 10/03/14
DATA=`date +"%D %H:%M "`
LOG="/var/log/check_proc.log"
[[ $# -ne 2 ]] && exit 1
PID_NAMES=$1
# get all PIDS as nn,nn,nn
get_pid()
{
if [[ ! "$PID_NAMES" =~ ^[0-9,]+$ ]] ; then
    PIDS=$(pgrep -d ',' -x $PID_NAMES)
else
    PIDS=$PID_NAMES
fi
}
get_pid
echo "PIDS: $PIDS MAX_CPU: $MAX_CPU"
echo "CPU_TOT|CURR_CPU|INFO"
MAX_CPU="$2"
MAX_CPU="$(echo "($MAX_CPU+0.5)/1" | bc)"
LOOP=1
while [[ $LOOP -eq 1 ]] ; do
   sleep 0.5s
#    sleep 10
    # Depending on your 'top' version and OS you might have to change head and tail line-numbers
    LINE="$(top -b -d 0 -n 1 -p $PIDS | head -n 8 \
        | tail -n 1 | sed -r 's/[ ]+/,/g' | \
        sed -r 's/^\,|\,$//')"
    # If multiple processes in $PIDS, $LINE will only match   the most active process
    CURR_PID=$(echo "$LINE" | cut -d ',' -f 1)
    # calculate cpu limits
    CURR_CPU_FLOAT=$(echo "$LINE"| cut -d ',' -f 9)
    CURR_CPU=$(echo "($CURR_CPU_FLOAT+0.5)/1" | bc)
    echo "PID $CURR_PID: $CURR_CPU""%"
    if [[ $CURR_CPU -ge $MAX_CPU ]] ; then
        INFO=`ps -p $CURR_PID -f|awk '{print $(NF-1)}'|awk -F/ '{print $NF}'|sed 's/TIME//g'`
        CPU_TOT=`iostat -c 2 1 |tail -n2 |head -n1 |awk '{print $1}'`
        DATA=`date +"%D %H:%M "`
        ALL_INFO="$DATA|$CPU_TOT|$CURR_CPU|$INFO"
        echo $ALL_INFO
        echo $ALL_INFO >> $LOG
        PID_NAMES=$1
        get_pid
        sleep 5
    fi
done
exit 0
Tags: , , , ,

1 thought on “script to monitor cpu usage by process

Leave a Reply

Your email address will not be published. Required fields are marked *