虽然service命令有点老了,但是redhat和centos上面还是在继续使用着,我的VPS也是使用的centos系统,而且httpd服务是我手动编译安装的,每次启动都需要很长的执行命令,心中有了能否直接用service命令来执行的想法,然后就上网搜了些资料,现真理出来,方便以后查看。
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文件下。
很多程序需要判断是否当前已经有一个实例在运行,这个目录就是让程序判断是否有实例运行的标志,比如说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
http://serverfault.com/questions/29788/what-is-needed-for-a-linux-service-to-be-supported-by-chkconfig