Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 正常關機偵測機制:rc.d 腳本建立/刪除旗標檔判斷關機狀態

編輯:Linux 教學

原理:開機時建立旗標檔 /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)。
  • K 腳本執行前會檢查 /var/lock/subsys/ 下是否有同名空檔 (如 touch /var/lock/subsys/rm-file),否則不執行。啟動腳本中需先建立該空檔。

此機制可納入監控系統,自動告警異常關機事件。

Copyright © Windows教程網 All Rights Reserved