创建Linux系统服务的方法

      由于最近项目需要将程序做成系统服务,在开机时就能够自动运行。所以在网上找了些资料写了这篇文章,以备后用。

      该方法在Ret Hat Enterprise Linux Server 5.5上测试成功。首先需要编写系统服务启动脚本,脚本大致如下:

 

#!/bin/bash

 

# test.sh

 

# chkconfig: 2345 20 81

# description: just for test

 

EXEC_PATH=/root/Server

EXEC=gnserver

PID_FILE=/var/run/test.sh.pid

DAEMON=/root/Server/gnserver

 

# Source function library.

. /etc/rc.d/init.d/functions

 

if ! [ -x $EXEC_PATH/$EXEC ] ; then

       echo "ERROR: $EXEC_PATH/$EXEC not found"

       exit 1

fi

 

stop()

{

       echo "Stoping $EXEC ..."

       killall $DAEMON >/dev/null

       rm -f $PID_FILE

       usleep 100

       echo "Shutting down $EXEC: [  OK  ]"     

}

 

start()

{

       echo "Starting $EXEC ..."

       $DAEMON > /dev/null &
       pidof $EXEC > $PID_FILE

       usleep 100

       echo "Starting $EXEC: [  OK  ]"        

}

 

restart()

{

       stop

       start

}

 

case "$1" in

       start)

       start

       ;;

 

       stop)

       stop

       ;;

 

       restart)

       restart

       ;;

 

       status)

       status -p $PID_FILE $DAEMON 

       ;;

  

       *)

       echo "Usage: service $EXEC {start|stop|restart|status}"

       exit 1

esac

exit $?

 

       以上脚本需要注意几个地方。#chkconfig后面三个参数分别表示服务在哪几个运行级别启动(本例是在2,3,4,5),在启动和关闭时服务脚本执行的优先级。#description是对该服务的描述。加上这两行之后才能用chkconfig命令添加服务。另外/etc/rc.d/init.d/functions这个脚本中包含了下面要用到的status这个函数,其用来打印当前服务进程的状态。/root/Server/gnserver是我们需要作为系统服务的程序。

       创建好脚本后将其放在/etc/rc.d/init.d这个目录下,我在这里将脚本命名为test.sh。然后修改脚本的属性使其可被执行:chmod 700 test.sh。最后利用chkconfig命令将其添加进系统服务: chkconfig --add test.sh。

      这样我们的程序就能在系统启动时自动在后台运行了。还可以使用命令service test.sh start马上启动该服务程序,用service test.sh status查看服务状态。

    

      此外还可以用下面的方法在系统启动时自动运行程序:

      如我们想自启动程序/root/Server/gnserver,则编辑/etc/rc.d/rc.local文件,在其后添加如下一行:/root/Server/gnserver > /dev/null &。则在系统启动后该程序将自动运行。

 

 

posted @ 2010-08-02 22:01  silverwings  阅读(2116)  评论(0编辑  收藏  举报