Wednesday, November 13, 2013

Shell script - Kill a specific program if its CPU load exceeded a certain threshold

This shell script I wrote in order to kill the python process if its CPU usage percentage exceeded 96%:


#! /bin/bash
THRESHOLD=96
while [ 1 ];
do
    MYPROGRAM_ID=`pidof python`
    # if the result is not empty, or there is a python process
    if [ ! -z "$
MYPROGRAM_ID" ] ; then
        CPU_LOAD=`ps -o %C -p $
MYPROGRAM_ID | tail -n 1`
        echo $CPU_LOAD
        # bc will return 0 for false and 1 for true
        if [ $(echo "$CPU_LOAD > $THRESHOLD" | bc) -ne 0 ] ; then
            kill -9 $GATEKEEPER_ID
        else
            echo "Normal"
        fi
    fi
done



Useful!