0

I was hoping someone could answer a question regarding this shell script that I've just gotten while taking over a website previously owned by someone else. This was their backup fix to catch any long running apache workers which their app did not kill correctly (the web server is only running this app and no other websites).

If this script is cronned to run every minute I believe that it kills /usr/sbin/httpd PIDs which are have been running longer than 60 minutes.


Primary question: I see MAXRUNMIN=60 as well as runTimeMin=$((runTimeSec / 60 )). Would both need to be changed to change this limit from 60 minutes to 30?

Followup question: I see it gets the list of PIDs byt doing grep "/usr/sbin/httpd". How can I add another process to this search as well. For example to not only grep and check to kill httpd PIDs but also another process say python PIDs.

#!/bin/sh

##number of minutes to allow a process to run
MAXRUNMIN=60
PIDS=`pgrep httpd|xargs echo -e`
nowSeconds=`date +%s`
#for i in `ps aux | grep -vE 'grep|root' | grep httpd | awk ' { print $9 "-" $2 } '`
for i in `ps aux | grep -vE 'grep|root' | grep "/usr/sbin/httpd" | awk ' { print $9 "-" $2 } '`
do
        procStart=`echo $i|awk -F"-" '{print $1}'`
        procId=`echo $i|awk -F"-" '{print $2}'`
        procSec=`date -d"$procStart" +%s`
        runTimeSec=$((nowSeconds - procSec))
        runTimeMin=$((runTimeSec / 60 ))
        if [ $runTimeMin -gt $MAXRUNMIN ]
        then
                echo $PIDS|grep -q $procId
                if [ $? -eq 0 ]
                then
                        echo "process ID $procId has been running loger than $MAXRUNMIN minutes"
                        kill -9 $procId
                fi
        fi
done
Analog
  • 202
  • 2
  • 12

1 Answers1

1

The author of your script was probable not aware of the possibilities of "ps", like "-u" (followed by a list of owners) or "-o etimes=" (giving elapsed time in seconds), which makes the task a lot simpler. I have a script, it's called "my_corona.sh", and it goes like this:

#! /usr/bin/ksh

# kills older processes

MCRNMAXMIN=60
MCRNPROGS="apache2|nginx"   # pipe separated list of executables
MCRNOWNERS="www-data"   # comma separated list of process owners


MCRNTIME=$(expr $MCRNMAXMIN \* 60)
ps -u $MCRNOWNERS -o pid=,etimes=,args= | grep -E "($MCRNPROGS)" \
| while read P T X
do
  if [ $MCRNTIME -lt $T ]
  then
     echo "$P $T $X  :: should be killed"
     kill -1 $P  # kill nicely
     sleep 5
     if kill -0 $P 2>/dev/null
     then
        echo "$P $T $X  :: didn't like it"
        kill -9 $P  # kill not so nicely
     fi
  # else
  #    echo "$P $T $X  :: should not be killed"
  fi
done
Gerard H. Pille
  • 2,569
  • 1
  • 13
  • 11