/etc/rc.local&&/etc/rc.d/init.d
Linux開機之後會執行/etc/rc.local檔案中的指令碼。
所以我們可以直接在/etc/rc.local中新增啟動指令碼
/etc/init.d/rc.local的內容
#! /bin/sh ### BEGIN INIT INFO # Provides:rc.local # Required-Start:$all # Required-Stop: # Default-Start:2 3 4 5 # Default-Stop: # Short-Description: Run /etc/rc.local if it exist ### END INIT INFO PATH=/sbin:/usr/sbin:/bin:/usr/bin . /lib/init/vars.sh . /lib/lsb/init-functions do_start() { if [ -x /etc/rc.local ]; then [ "$VERBOSE" != no ] && log_begin_msg "Running local boot scripts (/etc/rc.local)" /etc/rc.local ES=$? [ "$VERBOSE" != no ] && log_end_msg $ES return $ES fi } case "$1" in start) do_start ;; restart|reload|force-reload) echo "Error: argument '$1' not supported" >&2 exit 3 ;; stop) ;; *) echo "Usage: $0 start|stop" >&2 exit 3 ;; esac
從註釋可以看出該指令碼執行在2 3 4 5的啟動級別,只能處理start的引數,然後執行start,如果有/etc/rc.local檔案的話則執行/etc/rc.local。如果要把開機啟動的程式放/etc/init.d/rc.local檔案裡,記住千萬別一股腦寫檔案最後面就行了,因為在case語句塊裡指令碼就會退出。
/etc/rc.local內容
#!/bin/sh -e # # rc.local # # This script is executed at the end of each multiuser runlevel. # Make sure that the script will "exit 0" on success or any other # value on error. # # In order to enable or disable this script just change the execution # bits. # # By default this script does nothing. exit 0
這個腳本里面基本沒有內容,就是寫個模板讓你放開機自啟動程式的。把你的程式寫在exit 0行的前面就行了。
所以要新增開機啟動項,只需在/etc/rc.local檔案中新增就行了。
啟動級別:
0關機
1單使用者
2-5多使用者圖形介面
6重啟
對應每個啟動級別,/etc/目錄下都對應一個像/etc/rc5.d/這樣的目錄,下面是一些指令碼,這些指令碼基本都是對應/etc/init.d/目錄下的軟連結,命名裡面的數字代表優先順序,啟動時這些指令碼都會執行一遍。
可以看到“/etc/rc.d/init.d”下有很多的檔案,每個檔案都是可以看到內容的,其實都是一些shell指令碼。
系統服務的啟動就是通過“/etc/rc.d/init.d”中的指令碼檔案實現的。我們也可以寫一個自己的指令碼放在這裡。
指令碼檔案的內容也很簡單,類似於這個樣子(例如起個名字叫做“hahad”):
. /etc/init.d/functions start() { echo "Starting my process " cd /opt ./haha.sh } stop() { killall haha.sh echo "Stopped" }
寫了指令碼檔案之後事情還沒有完,繼續完成以下幾個步驟:
chmod +x hahad#增加執行許可權
chkconfig --add hahad#把hahad新增到系統服務列表
chkconfig hahad on#設定hahad的開關(on/off)
chkconfig --list hahad#就可以看到已經註冊了hahad的服務