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