Solved

PID autokill

Posted on 2011-03-22
6
548 Views
Last Modified: 2012-05-11
Hello,

Could somebody help with writing a cron script, that will check all running processes and kill those ones, which cpu usage is above 90% for example?

0
Comment
Question by:tanel
  • 4
  • 2
6 Comments
 
LVL 1

Expert Comment

by:crazyn3wf
ID: 35190208
Try this
#!/bin/bash
#
# Process control
#
# This shell-script watch that <process> doesn't pass the <limit> of % cpu usage
# If it does, the script kills that process and finish
#
# For linux kernel 2.6.x
# v.0.1 sept-2007
#
# Author: Miguel Ángel Molina Molina
# Licence: GPL v.2

# Parameter check
# [debug] parameter is optional and can be anything. If it exists, the script produces output to the screen for debugging purposes.
if [ $# -lt 2 -o $# -gt 3 ];
then
  echo "Usage: `basename $0` <process> <limit> [debug]"
  exit -1
fi

# [debug] exists?
if [ $# -eq 3 ];
then
  debug="yes"
else
  debug=""
fi

procpid=`pidof $1`
typeset -i limit=$2

# process existence check
if [ -z "$procpid" ];
then
  echo "Process: $1 doesn't exists"
  exit -1
fi

# limit check
if [ $limit -lt 1 -o $limit -gt 99 ];
then
  echo "Limit must be between 1 and 99"
  exit -1
fi

typeset -i hits=0

while [ 1 ]
do
  # Get usage cpu time
  typeset -i cputime=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # process pid check

  if [ ! -f /proc/${procpid}/stat ];
  then
    echo "Process doesn't exists: ${procpid}"
    exit -1
  fi
  # Get process usage cpu time
  typeset -i proctime=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # wait 5 seconds
  sleep 5
  # get usage cpu time, again
  typeset -i cputime2=`cat /proc/uptime | cut -f1 -d " " | sed 's/\.//'`
  # get process usage cpu time, again
  typeset -i proctime2=`cat /proc/${procpid}/stat | awk '{t = $14 + $15;print t}'`
  # calculate process usage cpu time over total usage cpu time as percentage
  typeset -i cpu=$((($proctime2-$proctime)*100/($cputime2-$cputime)))
  [ ! -z $debug ] && echo "Process $1, with pid: $procpid, is wasting: $cpu% of cpu"
  # limit exceed check
  if [ $cpu -gt $limit ];
  then
    # Count the excess
    let hits+=1
    if [ $hits = 1 ];
    then
      times="time"
    else
      times="times"
    fi
    [ ! -z $debug ] && echo "Process $1 has exceeded the limit: $limit ($cpu) $hits $times ..."
    # If hits are greater than 10, kill the process
    if [ $hits -gt 10 ];
    then
      echo -n "Killing process: $procpid ... "
      kill $procpid
      # wait until process die
      sleep 1
      # check if process has died
      if [ -z "`pidof $1`" ];
      then
        echo "Done."
      else
        echo "Can't kill the process."
      fi
      echo "Finished."
      exit 0
    fi
  else
   # if no limit exceed, reset hit counter
   let hits=0
  fi
done

Open in new window

0
 

Author Comment

by:tanel
ID: 35190539
Thank you, i will test it and let you know!
0
 

Author Comment

by:tanel
ID: 35192880
Sorry, it doesn't seem to work.. How to use it correctly ?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 1

Accepted Solution

by:
crazyn3wf earned 500 total points
ID: 35193152
ya it desent seem to take the PID correctly, guess i should have tested it before posting.
Try this one. its a little simpler

#!/bin/bash

# March-13-2006
# CPUuse trigger script by Noel
#
# bash code to watch a running program's CPU usage.
# if it's above a set value, it will auto send an email.
# You will need to set a Cron job to run this script every xx minutes
#
# Set some needed things:
#
processToWatch="convert" # in my case I need to watch convert
emailAddress="root@host" # this is my main emailaddress
triggerValue=90 # if the CPU use is above 90% send an email. DO NOT USE a DOT or COMMA!
tempFileName=tmp-cpu # some name of the temp file for the ps, grep data

ps auxww | grep "$processToWatch" | grep -v grep > /tmp/$tempFileName
export LINE
(
read LINE
while [ -n "$LINE" ]
do
set $LINE
read LINE
if [ $(echo "$3" | sed -e 's/\.[0-9]*//g') -gt $triggerValue ]; then
mail -s "CPU message alert for: $processToWatch" $emailAddress <<-END
This is to inform you that the following process: $processToWatch with PID (Process ID) $2 is now using more than your preset $triggerValue value.

Process: $processToWatch is using: $3 of CPU power!
The command used is: $11
END
fi
done
)< /tmp/$tempFileName

Open in new window

0
 

Author Comment

by:tanel
ID: 35196837
Heh, i need the script to kill any procces using much CPU, but this one is just sending mail..
0
 

Author Comment

by:tanel
ID: 35198026
Ok, i have edited the script a little bit and it kills now.
Thanks!
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

How to remove superseded packages in windows w60 or w61 installation media (.wim) or online system to prevent unnecessary space. w60 means Windows Vista or Windows Server 2008. w61 means Windows 7 or Windows Server 2008 R2. There are various …
It’s 2016. Password authentication should be dead — or at least close to dying. But, unfortunately, it has not traversed Quagga stage yet. Using password authentication is like laundering hotel guest linens with a washboard — it’s Passé.
Learn how to navigate the file tree with the shell. Use pwd to print the current working directory: Use ls to list a directory's contents: Use cd to change to a new directory: Use wildcards instead of typing out long directory names: Use ../ to move…
Connecting to an Amazon Linux EC2 Instance from Windows Using PuTTY.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now