掌握 Linux 啟動流程與自啟動配置機制,能精準控制服務啟動順序、運行級別與用戶環境初始化。
init(PID 1)讀取 /etc/inittab 決定預設運行級別rc.sysinit 完成系統級初始化(網路、Swap、主機名、檔案系統檢查等)/etc/rc.d/rc[0-6].d/ 中的啟動腳本鏈接getty 啟動終端登入提示,進入多用戶模式/etc/rc.d/init.d/ # 實際啟動腳本存放處
/etc/rc.d/rc[0-6].d/ # 各運行級別的啟動/停止鏈接
# 命名格式:
S##name # 啟動鏈接,傳遞 start 參數,## 為順序號(00-99)
K##name # 停止鏈接,傳遞 stop 參數
數字越小越早執行。S 開頭啟動,K 開頭關閉。
#!/bin/bash
# /etc/rc.d/init.d/apache
source /etc/sysconfig/rc
source $rc_functions
case "$1" in
start)
echo "Starting Apache daemon..."
/usr/local/apache2/bin/apachectl -k start
evaluate_retval
;;
stop)
echo "Stopping Apache daemon..."
/usr/local/apache2/bin/apachectl -k stop
evaluate_retval
;;
restart)
echo "Restarting Apache daemon..."
/usr/local/apache2/bin/apachectl -k restart
evaluate_retval
;;
status)
statusproc /usr/local/apache2/bin/httpd
;;
*)
echo "Usage: $0 {start|stop|restart|status}"
exit 1
;;
esac
cd /etc/rc.d/init.d
ln -sf ../init.d/apache ../rc0.d/K28apache
ln -sf ../init.d/apache ../rc1.d/K28apache
ln -sf ../init.d/apache ../rc2.d/K28apache
ln -sf ../init.d/apache ../rc3.d/S32apache
ln -sf ../init.d/apache ../rc4.d/S32apache
ln -sf ../init.d/apache ../rc5.d/S32apache
ln -sf ../init.d/apache ../rc6.d/K28apache
非標準但通用做法:
touch /etc/rc.d/rc.local
chmod +x /etc/rc.d/rc.local
# 在 rc.local 末尾加入啟動命令
ln -sf /etc/rc.d/rc.local /etc/rc.d/rc[1-5].d/S999rc.local
| 檔案 | 觸發時機 | 作用域 |
|---|---|---|
/etc/profile | 登入 Shell | 全域環境變數、PATH |
/etc/bashrc | 非登入互動 Shell | 全域別名、函數、提示符 |
~/.bash_profile | 登入 Shell | 用戶個人環境變數 |
~/.bashrc | 非登入互動 Shell | 用戶別名、函數 |
~/.bash_logout | 登出時 | 清理臨時檔案等 |
注意:Bash 腳本屬用戶會話層級,非系統服務層級。