Kill long running script, if it crosses the threshold time

Hi,

I need a script to kill the process if it running for long time.

Inputs for the scripts:
1.test.sh (will be running fron cron scheduler)
2.1 hr (ie threshold_time - if the test.sh is running for more than 1 hr test.sh has to kill)

Thanks,
Divya

Here's a basic concept that I wrote:

#!/bin/bash
#
# procWatch.sh
#
# -- script to check the elapsed time of a given
# -- process and if running longer than an hour
# -- kill the process
#

# check command-line for process name
if [ $# -ne 1 ]
then
    echo "Usage: ${0##*/} <process name>"
    exit 1
fi

# store the process name
proc=$1

# use ps command to list the processes and parse
# out our process
read etime pid prog <<<$(ps -eo etime,pid,args | grep $proc | grep -v grep)

# scrub the inputs
etime=$(echo $etime | awk -F'-' '{print $2}')
prog=$(echo $prog|awk '{print $1}')
prog=${prog##*/}

# convert hour time to seconds
hour=$(date --date="1:00:00" +%s)

# convert elapsed time to seconds
elapsed=$(date --date="$etime" +%s)

# compare the times
if [ $elapsed -gt $hour ]
then
    echo "[+] The $prog process has been running for over an hour."
    echo "[+] Killing process: $pid."
    kill $pid
else
    echo "[+] The $prog process has been running for $etime."
fi

# done
exit 0

d6adeb2db50f32cecbc8fc313292e797

1 Like