Add custom daemon on Linux System

Ubuntu add custom service(daemon)

Task

需要在系统启动的时候自动启动一个服务(后台程序),在系统关闭的时候关闭服务。
比如在部署某个应用之前,需要将某个任务设置成后台程序(daemon),而这些* 任务 *可以是Liunx command, 或者自己写的脚本。
比如在部署我的Django应用之前,需要启动MQ服务,一种可能的方式是:需要执行python manage.py runMQServer

Why dont use /etc/init.d

/etc/init.d是陈旧的方式,目前已经被淘汰,取而代之的是upstart
使用upstart方式添加后台程序配置更容易

/etc/init/run_mq.conf

以task中的需求为例,创建daemon的配置文件run_mq.conf:

# TMS MQ Service

description "TMS message queue server"
author "xxx <xxx@xxx.com>"


#the job is started automatically when the machine is first started (without writable filesystems or networking). 
start on startup

#the job is stoped automatically when the machine is shut down
stop on shutdown

#a job that exits quietly transitions into the stop/waiting state, no matter how it exited.
respawn

#respawn the job up to 2 times within a 5 second period.
#If the job exceeds these values, it will be stopped and
#marked as failed.
respawn limit 2 5

#controls where a job's output goes, and where its input comes from
console ouput

#additional shell code can be given to be run before the binary or script,it is intended for preparing the environment 
pre-start script
    #prepare environment
end script

script
    if [ -f /home/tms/TMS/tmsApp/management/commands/runMSGServer.py ]; then
        python /home/tms/TMS/manage.py runMSGServer
    fi
end script

#additional shell code can be given to be run after the binary or script,it is intended for cleaning up afterwards
post-stop script
    #clean up or else
	logger "TMS message queue server started..."
end script

references

How to correctly add a custom daemon to init.d?
Upstart getting started

原文地址:https://www.cnblogs.com/zeweiwu/p/5433816.html