首页 > 代码库 > Linux下新建服务

Linux下新建服务

1 首先在/etc/rc.d/init.d/下添加脚本 asr_cron

#!/bin/bash
# $Id: rc.redhat.asterisk 67061 2007-06-04 17:11:43Z tilghman $
#
# asterisk    Starts, Stops and Reloads Asterisk.
#
# chkconfig: 345 95 65
# description: Asterisk PBX and telephony daemon.
AST_SBIN=/var/www/html/test.php


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

if ! [ -x $AST_SBIN ] ; then
echo "ERROR: test not found"
exit 0
fi

DAEMON=$AST_SBIN

start() {
# Start daemons.
    echo -n $"Starting test: "
        $AST_SBIN >> /var/www/html/test.log &
        sleep 1
        proc=$(ps -fe | grep $AST_SBIN|grep -v grep|awk {print $2})
        if [ -z $proc ]
            then
                echo_failure
        else
            echo_success
                fi
                RETVAL=$?
                echo
                return $RETVAL
}

stop() {
# Stop daemons.
    RETVAL=1
        echo -n $"Shutting down test: "
        ps -fe | grep $AST_SBIN|grep -v grep|awk {print $2}|while read line
        do
            kill $line
                RETVAL=$?
                echo -n "kill $line "
                done
                sleep 1
                proc=$(ps -fe | grep $AST_SBIN|grep -v grep|awk {print $2})
                if [ -z $proc ]
                    then
                        echo_success
                else
                    echo_failure
                        fi
                        echo
                        return $RETVAL
}

restart() {
    stop
        start
}

status() {
    proc=$(ps -fe | grep $AST_SBIN|grep -v grep|awk {print $2})
        if [ -z $proc ]
            then
                echo "teset: test is stoped"
        else
            echo "test: test is starting"
                fi
                RETVAL=$?
                return RETVAL
}

# See how we were called.
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
status)
status
;;
*)
echo "Usage: service test {start|stop|restart|status}"
exit 1
esac

exit $?

这个脚本执行一个PHP脚本,功能有启动、停止、重启等功能。

test.php

 

#!/usr/bin/php -q
<?php
set_time_limit(0);
$file = ‘test.txt‘;

while(true)
{
@file_put_contents($file,date(‘Y-m-d H:i:s‘,time())."\n",FILE_APPEND);
sleep(10);
}

 

 

 

 

2 把上面的脚本加到服务里:

chkconfig --add asr_cron

3 需要把asr_cron脚本、以及PHP脚本赋予可执行权限

然后就可以如下的命令控制服务的启动、停止、重启了:

/etc/rc.d/init.d/asr_cron start

/etc/rc.d/init.d/asr_cron stop

/etc/rc.d/init.d/asr_cron restart

Linux下新建服务