Help with kill a specific process after certain running time

Hi,

Do anybody experience to write a bash script in order to kill a specific process (java) after certain time of running?

eg.

java java.jar task_run.txt

I will run a java program (java.jar) which will run a long list of process (task_run.txt) one by one.
I plan to terminate the java program if it is running a specific task more than 1 minute times.
Thus the java program can continue to run other task instead of stuck at particular process which taken long time.

Thanks for any advice.

# background process
java java.jar task_run.txt > /dev/null 2>&1   &
# take bg process id
PID=$!
# wait 60 s
sleep 60
# you can kill the process - if it's already stopped, then no problem
# send default signal TERM to the java process, it if's still working 
# = java can handle signal
kill $PID 2>/dev/null
sleep 2
# still process ? use signal KILL = and I mean it
kill -KILL $PID  2>/dev/null

Hi,

Thanks for advice.
I will have a try on it.
I just google and it shown that ulimit -t able to do similar task too?
But I just not sure how to specific only automatic kill the java program.
I got run few thing at the same time.
But I just wanna kill if a java process run more than 30 seconds.

Thanks a lot.

---------- Post updated at 10:47 AM ---------- Previous update was at 10:26 AM ----------

I was thinking to write a bash script with able to print out all my java program pid all the time and it only kill the java running if it was running more than 10 seconds.

Maybe something like following:

 
while sleep 10; do
  ps ax | grep "task_run.txt" | grep -v "grep" > line.txt
  if [ ! -s line.txt ]; then continue; fi
  minutes=`cat line.txt | cut -c 23 -d " "`
  pid=`cat line.txt | cut -f 1`
  if [ $minutes -gt 0 ]; then
    kill -9 $pid
    echo killed $pid
  fi
done

The "minutes" may be a little weak if the process continues to run but does not use cpu cycles. I think ps can be customized to display user time, if needed.

1 Like

Hi,

I need to monitor the file creation in some directory and i came to know that it can be achieved using ionotifywait tool but this is not available in Redhat 5.6

Do you have any idea wthether i can monitor the file without using inotifywait tool? Any other way to monitor the file creation file?

-Pawan

It is rude and inconsiderate to hijack another person's thread. You should start your own. Otherwise, confusion may ensue regarding to which problem a response pertains, particularly if the response doesn't quote an earlier post.

I encourage others to not respond to hijacks.

Regards,
Alister