我有脚本中的部分可能导致脚本因长时间运行命令而挂起。有没有办法如何监视脚本的提到部分是否长时间运行,如果是这样,那么杀死整个脚本。这应该是服务器,以防止让脚本永远运行。到目前为止我已经放了这样的东西,这种方法还行还是有更好的方法来做id,这是否可以避免使用互斥锁?
#!/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