#!/bin/bash
while true; do
process=$(ps -ef | grep /opt/tomcat7 | grep -v grep)
if [ -z "$process" ]; then
sleep 10
nohup /opt/tomcat7/bin/catalina.sh start & > /tmp/1.txt
fi
# 缺少 sleep!進程存在時無限循環
done
當 Tomcat 進程存在時,if 分支不執行,while 迴圈**無任何延遲**瘋狂執行 ps、grep、管道操作,佔滿 CPU。
#!/bin/bash
while true; do
if ! pgrep -f /opt/tomcat7 >/dev/null; then
sleep 10
nohup /opt/tomcat7/bin/catalina.sh start &> /tmp/tomcat_start.log
fi
sleep 5 # 關鍵:每輪檢查間隔 5 秒
done
pgrep 或 systemctl is-active 替代 ps | grep,效率更高。/tmp/1.txt 無限增長。