原理:開機時建立旗標檔 /tmp/check,正常關機時刪除。下次開機檢查檔案是否存在,即知上次是否正常關機。
開機建立旗標 — /etc/rc.d/init.d/touch-file.sh
#!/bin/sh
file=/tmp/check
if [ -e $file ]; then
echo "this is not normal shutdown" >> /var/log/checkmessage
else
echo "this is normal shutdown and touch file" >> /var/log/checkmessage
touch $file
fi
關機刪除旗標 — /etc/rc.d/init.d/rm-file.sh
#!/bin/sh
file=/tmp/check
echo "this is normal shutdown and rm file" >> /var/log/checkmessage
rm -rf $file
# 關機/重啟執行 (K 開頭)
ln -s /etc/rc.d/init.d/rm-file.sh /etc/rc.d/rc0.d/K01rm-file
ln -s /etc/rc.d/init.d/rm-file.sh /etc/rc.d/rc6.d/K01rm-file
# 開機執行 (S 開頭)
ln -s /etc/rc.d/init.d/touch-file.sh /etc/rc.d/rc3.d/S01touch-file
# 若有圖形介面,亦需加入 rc5.d
K01rm-file vs rm-file.sh)。/var/lock/subsys/ 下是否有同名空檔 (如 touch /var/lock/subsys/rm-file),否則不執行。啟動腳本中需先建立該空檔。此機制可納入監控系統,自動告警異常關機事件。