title: Kill process using constant high CPU
body: <p>Using the following bash script that does the job just fine when it comes to killing the process if it reaches 70% CPU usage, however, since the process can legit use that much CPU for a short period of time I am getting false-positives and the process is getting killed even though I don't want to. The script makes use of the time (in seconds) but it only counts it as the process uptime and not as the high CPU usage for that amount of seconds.</p>
  <p>I am trying so the process only gets kill if it uses 70% CPU or more for a constant 30 seconds or more, should the process use &gt;70% CPU for a few seconds only then the process shouldn't be killed.</p>
  <p>I'm looking to implement this directly into the script and not via a 3rd party application like monit.</p>
  <pre><code>#!/bin/bash
  
  #max cpu % load
  MAX_CPU=70
  #max execution time for CPU percentage &gt; MAX_CPU (in seconds)
  MAX_SEC=30
  #sort by cpu
  SORTBY=9
  
  #define a processes command name to check
  declare -a KILLLIST
  KILLLIST=(&quot;CSS2&quot;)
  
  #iterate for each process to check in list
  for PROCESS_TOCHECK in ${KILLLIST[*]}
  do
  
      #retrive pid with top command order by SORTBY
      PID=$(top -bcSH -n 1 | grep $PROCESS_TOCHECK | sort -k $SORTBY -r | head -n 1 | awk '{print $1}')
  
      CPU=$(top -p $PID -bcSH -n 1 | grep $PROCESS_TOCHECK | sort -k $SORTBY -r | head -n 1 | awk '{print $9}')
      TIME_STR=$(top -p $PID -bcSH -n 1 | grep $PROCESS_TOCHECK | sort -k $SORTBY -r | head -n 1 | awk '{print $11}')
  
      #format integer cpu
      CPU=${CPU%%[.,]*}
      
      # Decode the top CPU time format [dd-]hh:mm.ss.
      TIME_SEC=0
      IFS=&quot;-:&quot; read c1 c2 c3 c4 &lt;&lt;&lt; &quot;$TIME_STR&quot;
  
      #with top command time format is hh:mm.ss, so truncare seconds in c2
      c2=${c2%%.*}
  
      if [ -n &quot;$c4&quot; ]
      then
        TIME_SEC=$((10#$c4+60*(10#$c3+60*(10#$c2+24*10#$c1))))
      elif [ -n &quot;$c3&quot; ]
      then
        if [ &quot;$CMD&quot; = &quot;ps&quot; ]; then
          TIME_SEC=$((10#$c3+60*(10#$c2+60*10#$c1)))
        else
          TIME_SEC=$(((10#$c3*24)*60*60)+60*(10#$c2+60*10#$c1))             
        fi   
      else
        if [ &quot;$CMD&quot; = &quot;ps&quot; ]; then
          TIME_SEC=$((10#0+(10#$c2+60*10#$c1)))
        else
          TIME_SEC=$((10#0+60*(10#$c2+60*10#$c1)))
        fi
      fi
  
      #check if need to kill process
      if [ $CPU -gt $MAX_CPU ] &amp;&amp; [ $TIME_SEC -gt $MAX_SEC ]; then
          kill -9 $PID
      fi
  
  done
  </code></pre>