Listing 1 timeout_countdown
#!/bin/ksh
# timeout_countdown:
# kill the parent process if the user has not entered input within
# a given time frame.
integer timeout=300
integer pid=0
directory=/tmp
while getopts d:p:t: option
do
case $option in
d)
directory=$OPTARG
;;
p)
pid=$OPTARG
;;
t)
timeout=$OPTARG
;;
esac
done
shift $(($OPTIND - 1))
readonly operand=$1
if [[ -z $operand ]]
then
exit 1
fi
if [[ $pid -eq 0 ]]
then # determine parent process id if none passed
pid=$(echo $(ps -p $$ -o ppid | tail -1))
fi
timeout_file=$directory/.timeout_countdown.$pid
case $operand in
start)
echo $$ > $timeout_file
sleep $timeout
rm -f $timeout_file
kill -15 $pid 2>&- >&-
;;
stop)
if [[ -f $timeout_file ]]
then
pid=$(cat $timeout_file)
command=$(ps -o args -p $pid | tail -1)
# 2nd field is the timeout_countdown command
command=$(echo "$command"|cut -d " " -f2)
if [[ $(basename $0) == $(basename $command) ]]
then
kill -9 $pid 2>&- >&-
rm -f $timeout_file
fi
fi
;;
*)
exit 1
;;
esac
exit 0
|