核心思路:開機建立標記檔,正常關機刪除標記檔。下次開機檢查標記檔是否存在,即可判斷上一次關機是否正常。本文提供完整腳本、部署位置、Runlevel 連結規則與關鍵陷阱說明。
#!/bin/sh
file=/tmp/check
if [ -e "${file}" ]; then
echo "$(date): this is not normal shutdown" >> /var/log/checkmessage
else
echo "$(date): this is normal shutdown and touch file" >> /var/log/checkmessage
touch "${file}"
fi
#!/bin/sh
file=/tmp/check
echo "$(date): this is normal shutdown and rm file" >> /var/log/checkmessage
rm -f "${file}"
# 關機執行(Runlevel 0)
ln -s /etc/rc.d/init.d/rm-file.sh /etc/rc.d/rc0.d/K01rm-file
# 開機執行(Runlevel 3,多用戶文字模式)
ln -s /etc/rc.d/init.d/touch-file.sh /etc/rc.d/rc3.d/S01touch-file
注意:純文字模式伺服器無需部署至 rc5.d(圖形模式)。
stop。start。編號(如 01、99)控制執行順序,數字越小越優先。
系統執行 K 腳本前,會檢查 /var/lock/subsys/ 下是否存在同名空檔案。若不存在,腳本不會執行。因此必須建立對應鎖檔:
cd /var/lock/subsys
touch rm-file # 與 K 腳本檔名一致(rm-file.sh → rm-file)
此機制確保只有已啟動的服務才會在關機時正確停止。
K01rm-file vs rm-file.sh),避免混淆。此法零依賴、極簡易,適合嵌入式、伺服器等無人值守環境監控關機完整性。