Linux: autokill a crashed / infinite loop process

Sometime a process can take 100% of all available cpu power because it crashed. Here is a little script I used on a server for pdftk because this software was crashing from time to time.

Just launch the script from a cron job and replace “PROCESS_NAME” by the name of the process to watch.

  • argument 1 : number of minutes after which the process will be killed
  • argument 2 : number of seconds
#!/bin/bash
 
# get process id and execution time
process=`top -b -n 1 | grep PROCESS_NAME | awk '{print $1" "$11}'`
 
# extract pid
pid=`echo $process | awk '{print $1}'`
 
# extract execution time
time=`echo $process | awk '{print $2}' | awk -F ":" '{ min=$1; sec=$2; print 60*min+sec}'`
 
if [ $(echo "$time > 1"|bc) -eq 1 ] ;  then
  kill -9 $pid
  echo "killed process $pid that used $time of processor power"
fi

Leave a Reply

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

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.