Linux開機之后會執(zhí)行/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的參數(shù),然后執(zhí)行start,如果有/etc/rc.local文件的話則執(zhí)行/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/目錄下的軟鏈接,命名里面的數(shù)字代表優(yōu)先級,啟動時這些腳本都會執(zhí)行一遍。
可以看到“/etc/rc.d/init.d”下有很多的文件,每個文件都是可以看到內容的,其實都是一些shell腳本。
系統(tǒng)服務的啟動就是通過“/etc/rc.d/init.d”中的腳本文件實現(xiàn)的。我們也可以寫一個自己的腳本放在這里。
腳本文件的內容也很簡單,類似于這個樣子(例如起個名字叫做“hahad”):
. /etc/init.d/functions
start() {
echo "Starting my process "
cd /opt
./haha.sh
}
stop() {
killall haha.sh
echo "Stopped"
}
寫了腳本文件之后事情還沒有完,繼續(xù)完成以下幾個步驟:
chmod +x hahad #增加執(zhí)行權限
chkconfig --add hahad #把hahad添加到系統(tǒng)服務列表
chkconfig hahad on #設定hahad的開關(on/off)
chkconfig --list hahad #就可以看到已經(jīng)注冊了hahad的服務