Centos手動編寫service命令腳本
一.動機
雖然service命令有點老了,但是redhat和centos上面還是在繼續使用着,我的VPS也是使用的centos系統,而且httpd服務是我手動編譯安裝的,每次啓動都需要很長的執行命令,心中有了能否直接用service命令來執行的想法,然後就上網搜了些資料,現真理出來,方便以後查看。
二.知識
1.service man幫助文檔:
service(8) service(8)
NAME
service – run a System V init script
SYNOPSIS
service SCRIPT COMMAND [OPTIONS]
service –status-all
service –help | -h | –version
DESCRIPTION
service runs a System V init script in as predictable environment as possible, removing
most environment variables and with current working directory set to /.
The SCRIPT parameter specifies a System V init script, located in /etc/init.d/SCRIPT.
The supported values of COMMAND depend on the invoked script, service passes COMMAND and
OPTIONS it to the init script unmodified. All scripts should support at least the start
and stop commands. As a special case, if COMMAND is –full-restart, the script is run
twice, first with the stop command, then with the start command.
service –status-all runs all init scripts, in alphabetical order, with the status com-
mand.
FILES
/etc/init.d
The directory containing System V init scripts.
ENVIRONMENT
LANG, TERM
The only environment variables passed to the init scripts.
SEE ALSO
chkconfig(8), ntsysv(8)
Jan 2006 service(8)
(END)
存在即合理,man幫助文檔其實已經給了我們很多有用的信息,1.service是用來執行一個腳本的命令,格式爲:service 腳本 命令
2.這些腳本都放在/etc/init.d文件下。
2./var/lock目錄
很多程序需要判斷是否當前已經有一個實例在運行,這個目錄就是讓程序判斷是否有實例運行的標誌,比如說xinetd,如果存在這個文件,表示已經有 xinetd在運行了,否則就是沒有,當然程序裏面還要有相應的判斷措施來真正確定是否有實例在運行。通常與該目錄配套的還有/var/run目錄,用來存放對應實例的PID,如果你寫腳本的話,會發現這2個目錄結合起來可以很方便的判斷出許多服務是否在運行,運行的相關信息等等。
來源: <http://sunxiaqw.blog.163.com/blog/static/9906543820111184422807/>
從這段文字基本就能判斷出/var/lock目錄的作用了,其實我個人的簡單理解就是用來判斷進程的唯一性,在/var/lock/subsys中創建一個文件,來標識進程已創建,當執行service httpd start時,腳本判斷是否在/var/lock/subsys下存在相應的文件,若存在則說明進程已經在執行,無需創建。
三.腳本創建
[bash]#!/bin/bash
#chkconfig: 2345 10 90 ##這一行一定要加,格式爲chkconfig:#description:httpd service . /etc/init.d/functions ##functions裏面有system v的環境變量設置,腳本中也需要 HTTPD=httpd start(){ ##ps -aux|grep -i httpd|grep -v grep>/dev/null if [ -f /var/lock/subsys/$HTTPD ]; then echo "httpd is running…" else echo "httpd is starting…" ./opt/httpd2\.4/bin/httpd -k start touch /var/lock/subsys/httpd sleep 2 echo "httpd start OK." fi } stop(){ if [ -f /var/lock/subsys/$HTTPD ];then echo "Stopping httpd …" ./opt/httpd2\.4/bin/httpd -k stop rm -f /var/lock/subsys/httpd sleep 2 echo "httpd stop OK." else echo "httpd is not running…" fi } restart(){ stop start } case "$1" in start) start;; stop) stop;; restart) restart;; *) echo $"Usage: ${HTTPD} {start|stop|restart}" exit 1 ;; esac
[/bash]
本實驗關閉httpd是用的httpd自帶命令,也可以使用killproc httpd來替代./opt/httpd2\.4/bin/httpd -k stop命令。此service啓動腳本可以加入chkconfig中,使用chkconfig –add httpd即可加入。
參考
http://www.linuxso.com/command/chkconfig.html
http://sunxiaqw.blog.163.com/blog/static/9906543820111184422807/
http://linux.about.com/od/lsa_guide/a/gdelsa20.htm