Linux 有一套完整的啟動體系,把脈絡抓住之後,開機過程就不再神祕,也能自己決定什麼服務要在開機時跑起來。
本文假設 /etc/inittab 中設定的執行層級目錄為:
/etc/rc.d/rc0.d /etc/rc.d/rc1.d /etc/rc.d/rc2.d /etc/rc.d/rc3.d /etc/rc.d/rc4.d /etc/rc.d/rc5.d /etc/rc.d/rc6.d /etc/rc.d/init.d
init 是所有程序的頂層。它讀取 /etc/inittab,執行 rc.sysinit 腳本(注意檔名不一定相同,有些 Unix 甚至把語句直接寫在 inittab 裡)。
rc.sysinit 做了大量前置工作:
init $PATH config network start swap function set hostname check root file system, repair if needed check root space ....
接著 rc.sysinit 依 inittab 的設定去執行各 rc?.d 目錄。Linux 是多使用者系統,getty 是「單使用者」與「多使用者」的分水嶺;在 getty 之前跑的都是系統層級腳本。
所有啟動腳本放在 /etc/rc.d/init.d 下,而各 rc?.d 目錄裡放的是指向 init.d 的連結,命名格式為:
S{number}{name} # S 開頭:向腳本傳遞 start 參數
K{number}{name} # K 開頭:向腳本傳遞 stop 參數
number 決定執行順序,數字小的先跑。
以下是啟動 httpd 的 /etc/rc.d/init.d/apache 片段:
#!/bin/bash ......
它接受 start、stop、restart、status 等參數。接著建立各層級的連結:
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
也就是在 0/1/2/6 執行層級關閉它,在 3/4/5 啟動它。手動做這些連結很麻煩,RHEL 系可用 chkconfig --add/--level 代勞。
常用的 rc.local 其實只是習慣問題,並非標準。各發行版實作不同,可以自己補齊:
touch /etc/rc.d/rc.local chmod +x /etc/rc.d/rc.local ln -sf /etc/rc.d/rc.local /etc/rc.d/rc1.d/S999rc.local && ln -sf /etc/rc.d/rc.local /etc/rc.d/rc2.d/S999rc.local && ln -sf /etc/rc.d/rc.local /etc/rc.d/rc3.d/S999rc.local && ln -sf /etc/rc.d/rc.local /etc/rc.d/rc4.d/S999rc.local && ln -sf /etc/rc.d/rc.local /etc/rc.d/rc5.d/S999rc.local && ln -sf /etc/rc.d/rc.local /etc/rc.d/rc6.d/S999rc.local
用 S999 是為了讓它最後執行,確保網路等服務都已就緒。把要自啟動的指令寫進這個檔案即可,例如 /sbin/service crond start。
/etc/profile /etc/bashrc ~/.bash_profile ~/.bashrc
這幾個是 bash 的啟動腳本,通常用來設定「單一使用者」的環境,也能實現登入時自動執行某支程式。但要清楚:它們屬於 bash 的範疇,而不是系統範疇——只有使用者登入才會觸發,服務在開機過程中不會執行它們。
實務上的判斷很簡單:要開機就執行、不依賴登入,寫進 init.d 腳本或 rc.local;要每個登入者都套用,寫進 /etc/profile。