1

I have the part in script that might cause the script hang due to very long running command. Is there a way of how to monitor if mentioned section of script is running for long time and if so then kill whole script. This should server as a prevention of having the script that is running forever. So far I've put something like this, is this approach OK or is there any better way to do id, does this avoid Mutexes?

#!/bin/bash

func_watchdog () {
  echo "SCRIPT IS RUNNING FOR LONG TIME, I'M GOING TO TERMINATE IT"
  kill $MAIN_PID
  exit 1
} 

trap func_watchdog TERM
MAIN_PID=$$
TRESHOLD=10

echo "I'M SETTING UP WATCHDOG THAT WILL MONITOR IF CRITICAL PART OF THE SCRIPT WONT OVERCOME THE TIME TRESHOLD"
(sleep $TRESHOLD && kill "$MAIN_PID")&
WATCHDOG_PID=$!

echo "HERE COMES THE CRITICAL PART OF THE SCRIPT THAT MIGHT TAKE LONG"
for i in `seq 1 5`; do
# while true; do
  date
  sleep 1
done

echo "THE CRITICAL PART ENDED SUCCESFULLY, WATCHDOG IS NOT NEEDED ANYMORE"
kill "$WATCHDOG_PID"
exit 0
Wakan Tanka
  • 7,542
  • 16
  • 69
  • 122
  • `man timeout`, assuming whatever distribution you are using has it, although you may need to install it if it's not in the default base install, as well... – twalberg May 12 '15 at 21:02
  • can you post equivalent code to mine but using `timeout` command ? – Wakan Tanka May 12 '15 at 21:21
  • the problem that I see with using timeout is how to pass larger block of code as argument? I suppose functions can be used for this but does it have some benefit over solution that I've posted in, performance, speed, readability, scalability? – Wakan Tanka May 12 '15 at 21:41
  • Also this `timeout $TRESHOLD func_critical` ended with `timeout: failed to run command 'func_critical': No such file or directory` – Wakan Tanka May 12 '15 at 21:59
  • See here for an answer: http://stackoverflow.com/questions/11935130/how-to-use-timeout-command-with-a-own-function – Tim May 13 '15 at 00:52

0 Answers0