check if job still alive and killing it after a certain walltime

Hi!

I'm using a script to start a process that might run forever if some parameters are given wrong (it's part of an optimization). I would now like to have the process killed after a certain walltime in that case. So far I get it done with the following lines

./My_process.e &
pid=`ps -ef | grep $$ | grep My_programme.e | grep -v grep | awk '{print $2}'`
sleep $Walltime
if kill -0 $pid 2>/dev/null;then
kill -TERM $pid
fi

This works but is not very convenient as the shell always is in sleep mode for $Walltime seconds, even if "My_process" runs properly and finishes after say 15 seconds. As I am calling this programme several hundred times and the walltime currently is 25 seconds it takes very long. It would be nice if the script would continue when the process is running properly and finishes by itself. I thought of something like "while sleep..." but can't figure it out....is there any way to do it like that or are there other nice ways?
Thankful for any hint,
ciwstevie

A thought.

Use ps with -o lstart option. It is supposed to show you the start times. Get that time, and then see if 15 seconds has elapsed or not. You can avoid the sleep altogether.

Will require some scripting effort tho'.

Vino

Probably the easiest way would be to pipe out the 'time' seconds from a date command (date +"%S") at execution of script, then run a check on that (+your time) with a count/do loop.

I'd do the script, but can't be arsed right now :slight_smile:

Here's the code that made it finally work....although I have to admit that it wasn't me who did it...thanks Steve :slight_smile:

./My_process.e &
pid=`ps -ef | grep $$ | grep My_process.e | grep -v grep | awk '{print $2}'`
count=0
Walltime=30
while kill -0 $pid 2> /dev/null
do
sleep 1
count=`expr $count + 1`
if [ $count -gt $Walltime ] ; then
kill -TERM $pid 2> /dev/null
break
fi
done

Maybe somebody might make use of it as well....

Best regards,

CIWStevie