前言#
我們在linux上要啟動一個程序得時候, 往往都是要寫一堆路徑, 找到要啟動得服務程序, 再用 ./*** 啟動服務. 那么我們有沒有快速啟動方法嗎, 答案是肯定得
service 介紹#
官方介紹(英文): https://linux.die.net/man/8/service
簡單說一下service運行過程. 以iptables為例: service iptables start
- 首先,sevice 會去/etc/init.d下尋找iptables腳本, start是iptables腳本里的一個參數(你可以去查看networking這個腳本支持的參數)
- 然后告訴系統運行iptables這個腳本,剩下的事情就交給iptables腳本去坐了,事實就是這么簡單。
至此,你們應該知道如何添加一個service命令了吧
編寫一個腳本,然后把它放在/etc/init.d這個目錄下,再用service + 腳本名字 運行即可。如果是要開機自動啟動那就得用chkconfig命令了
注意:
A、service這個命令往往是即時生效,不用開關機,但是重啟后服務會回到默認狀態。
B、在init.d里面得腳本是沒有后綴名的
設置開機自動啟動#
chkconfig --add test chkconfig test on/off //重啟后永久生效
上面的不生效:則使用下面得方法
通過update-rc.d 命名設置開機自啟動
cd /etc/init.d sudo update-rc.d test defaults 95
注:其中數字95是腳本啟動的順序號,按照自己的需要相應修改即可。在你有多個啟動腳本,而它們之間又有先后啟動的依賴關系時你就知道這個數字的具體作用了。該命令的輸出信息參考如下:
update-rc.d: warning: /etc/init.d/test missing LSB information update-rc.d: see <http://wiki.debian.org/LSBInitScripts> Adding system startup for /etc/init.d/test ... /etc/rc0.d/K95test -> ../init.d/test /etc/rc1.d/K95test -> ../init.d/test /etc/rc6.d/K95test -> ../init.d/test /etc/rc2.d/S95test -> ../init.d/test /etc/rc3.d/S95test -> ../init.d/test /etc/rc4.d/S95test -> ../init.d/test /etc/rc5.d/S95test -> ../init.d/test
卸載啟動腳本的方法:
cd /etc/init.d sudo update-rc.d -f test remove
命令輸出的信息參考如下:
Removing any system startup links for /etc/init.d/test ... /etc/rc0.d/K95test /etc/rc1.d/K95test /etc/rc2.d/S95test /etc/rc3.d/S95test /etc/rc4.d/S95test /etc/rc5.d/S95test /etc/rc6.d/K95test
常見錯誤:#
1. service啟動任務時提示: program-service: unrecognized service
這是因為我們還沒有更改 執行腳本得 的權限為可執行。chmod +x /etc/init.d/serviceName
后重新執行上一個命令
2. 添加到開機啟動任務時提示: service *** does not support chkconfig
[root@redis01 test]# chkconfig --add test service test does not support chkconfig 解決方法:(在/etc/init.d/test添加兩行注釋) #!/bin/sh #添加的兩行注釋內容如下: # chkconfig: 2345 90 10 # description: test is a persistent key-value database # 注釋的意思是,test服務必須在運行級2,3,4,5下被啟動或關閉,啟動的優先級是90,關閉的優先級是10 [root@redis01 test]# chkconfig --add test [root@redis01 test]# echo $? 0 [root@redis01 test]# chkconfig --list | grep test test 0:off1:off2:on3:on4:on5:on6:off
在編輯其它類似服務時,也可能出現這種情況,解決方法基本類似