您的位置:首页 > 运维架构 > Linux

Linux 开机自动启动服务

2014-07-15 13:49 274 查看

启动脚本

启动脚本示例 https://github.com/cyclops26/service-scripts/blob/master/genericServiceScript
#!/bin/bash
#
# APPLICATION_NAME      This shell script takes care of starting and stopping APPLICATION_NAME
#
# chkconfig: - 80 20
#
### BEGIN INIT INFO
# Provides: APPLICATION_NAME
# Required-Start: $network
# Required-Stop: $network
# Default-Start:     3 4 5
# Default-Stop:      0 1 2 6
# Short-Description: APPLICATION_NAME daemon
# Description:       Starts the APPLICATION_NAME daemon.
### END INIT INFO
#
# Author: Eli Keimig
# Copyright: GPL 2012

# VARIABLES
USER="root"
NAME="Application_Name"
BIN="/usr/bin"
CONTAINER="${BIN}/CONTAINER" # REPLACE "CONTAINER" with something like "perl, bash, or python"
PROGRAM="Script_to_Execute"
START_ARGS="-d"
NAME="Container for ${NAME}"
LOG="/var/log/${NAME}_Service.log"
HOME="/apps/serviceDirectory"
WAIT_TIME=60

# EXECUTION

function start {
PID=`/bin/ps -ef | grep "${PROGRAM}" | grep -v "grep" | awk '{print $2}'`
if [ ${PID} ]
then
/bin/echo "${NAME} is already started"
else
/bin/echo "Starting ${NAME}..."
su ${USER} -c "${CONTAINER} ${HOME}/${PROGRAM} ${START_ARGS}" >> ${LOG} 2>&1 &
/bin/echo "${NAME} will be up shortly..."
/bin/sleep 5
PID_VALIDATE=`/bin/ps -ef | grep "${PROGRAM}" | grep -v "grep" | awk '{print $2}'`
if [ ${PID_VALIDATE} ]
then
/bin/echo "${NAME} is now running"
else
/bin/echo "${NAME} failed to start - Please check ${LOG} for more information"
fi
fi
}

function stop {
/bin/echo "Stopping ${NAME}..."

PID=`/bin/ps -ef | grep "${PROGRAM}" | grep -v "grep" | awk '{print $2}'`
if [ ${PID} ]
then
/bin/echo "${NAME} is stopping.."

/bin/su ${USER} -c "/bin/kill -15 ${PID}" >> ${LOG} 2>&1 &

MAX_TRIES=$((WAIT_TIME/5))

while [ true ]; do
if [ -z ${PID} ]
then
/bin/echo "Stopped ${NAME}"
break;
fi

/bin/echo "."

((tries ++))
if [ ${tries} -ge ${MAX_TRIES} ]
then
/bin/echo "Process not responding..."
/bin/echo "Killing process..."
/bin/kill -9 ${PID}
fi

/bin/sleep 5;
PID=`/bin/ps -ef | grep "${PROGRAM}" | grep -v "grep" | awk '{print $2}'`
done;

else
/bin/echo "${NAME} is not running"
fi
}

function status {
PID=`/bin/ps -ef | grep "${PROGRAM}" | grep -v "grep" | awk '{print $2}'`
if [ ${PID} ]
then
/bin/echo "${NAME} is running"
else
/bin/echo "${NAME} is not running"
fi
}

case $1 in
start)
start
;;
restart)

stop

start

;;
status)
status
;;
stop)
stop
;;
esac


centos/redhat使用chkconfig管理系统服务
1)将启动脚本拷贝到/etc/init.d目录下,假设脚本名称为 my-script

2)添加自己的系统服务
# chkconfig --add my-script

3)修改系统服务在不同level下的开关状态
# chkconfig  [--level [123456] ]  [服务名]  [on | off]

4)查看服务
 # chkconfig --list  [服务名]

ubuntu

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: