歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> 使Linux系統上的程序開機後自動運行

使Linux系統上的程序開機後自動運行

日期:2017/3/1 18:10:20   编辑:Linux技術
Linux有自己一套完整的啟動體系,抓住了Linux啟動的脈絡,Linux的啟動過程將不再神秘。
閱讀之前建議先看一下附圖。
本文中假設inittab中設置的init tree為:
/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
1. 關於Linux的啟動
init是所有進程之父
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之前運行的是系統腳本
. 關於rc.d
所有啟動腳本放置在 /etc/rc.d/init.d下
rc?.d中放置的是init.d中腳本的鏈接,
命名格式是:
S{number}{name}
K{number}{name}
S開始的文件向腳本傳遞start參數
K開始的文件向腳本傳遞stop參數
number決定執行的順序
3. 啟動腳本示例
這是一個用來啟動httpd的 /etc/rc.d/init.d/apache 腳本:
代碼:
#!/bin/bash
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可以看出他接受start,stop,restart,status參數
然後可以這樣建立rc?.d的鏈接:
代碼:
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/K28apache4. 關於rc.local
經常使用的 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.local5. 關於bash啟動腳本
/etc/profile
/etc/bashrc
~/.bash_profile
~/.bashrc
是bash的啟動腳本
一般用來設置單用戶的啟動環境,也可以實現開機單用戶的程序,但要明確他們都是屬於bash范疇而不是系統范疇。
他們的具體作用介紹如下:
/bin/bash這個命令解釋程序(後面簡稱shell)使用了一系列啟動文件來建立一個運行環境:
/etc/profile
/etc/bashrc
~/.bash_profile
~/.bashrc
~/.bash_logout
每一個文件都有特殊的功用並對登陸和交互環境有不同的影響。
/etc/profile 和 ~/.bash_profile 是在啟動一個交互登陸shell的時候被調用。
/etc/bashrc 和 ~/.bashrc 是在一個交互的非登陸shell啟動的時候被調用。
~/.bash_logout 在用戶注銷登陸的時候被讀取
一個交互的登陸shell會在 /bin/login 成功登陸之後運行。一個交互的非登陸shell是通過命令行來運行的,如[prompt] $/bin/bash。一般一個非交互的shell出現在運行shell腳本的時候。之所以叫非交互的shell,是因為它不在命令行上等待輸入而只是執行腳本程序。
Copyright © Linux教程網 All Rights Reserved