Check task cpu usage from shell script ?



  • From a shell script, is there a way to determine if the current CPU usage of a specified task is over 30%, then perform an action?
    Thanks!



  • What shell script language(s) does pfSense Embedded version have built in?
    Where may I find the best Cheat Sheet and Manual for it?
    Thank you, -pc



  • pfSense has
    tcsh
    and normal sh

    Check the online FreeBSD man pages.



  • Okay, took a moment to figure this out.  Thanks to Bill M for the integer idea.

    Here's the deal, we have no utilities in the current installs to calculate long integers from the shell so I modified the snapshot server and future versions to include the bc utility.

    Anyhoo, in an hour install the latest snapshot then test this script:

    #!/bin/sh
    PROGS_TO_TEST_FOR="make top ls script screen cvs cvsup"
    for processing in $PROGS_TO_TEST_FOR; do
            CPUUSAGE=`ps awux | grep $processing | awk '{ print $3 }' | tail -n1`
            CPUUSAGEB=`echo 100 \* $CPUUSAGE | bc`
            echo $CPUUSAGEB
            if [ $CPUUSAGEB -gt 30 ]; then
                    echo "$processing is using more than 30"
            fi
    done
    


  • Thank you, S.Ullrich & Bill.M!  I'll try that script next time we re-flash.

    I haven't yet managed to locate the "sh" manual on freebsd.org; nothing so far on search engines either, "sh" is a nondistinctive term.
    Thanks, -pc



  • Here's an updated version.

    #!/bin/sh
    PROGS_TO_TEST_FOR="make top ls script screen cvs cvsup"
    for processing in $PROGS_TO_TEST_FOR; do
            CPUUSAGE=`ps awux | grep $processing | grep -v grep | awk '{ print $3 }' | tail -n1`
            CPUUSAGEB=`echo 100 \* $CPUUSAGE | bc`
            RUNNINGCMD=`ps awux | grep $processing | grep -v grep | awk '{ print $11 }' | tail -n1`
            PID=`ps awux | grep $processing | grep -v grep | awk '{ print $2 }' | tail -n1`
            if [ $CPUUSAGEB -gt 30 ]; then
                    echo "$PID $RUNNINGCMD using more than 30 cpu. restarting"
                    kill $PID
                    exec $RUNNINGCMD
            fi
    done
    

Log in to reply