放置shell脚本在systemd控制下

假设我有这样的shell脚本:

#!/bin/sh # cherrypy_server.sh PROCESSES=10 THREADS=1 # threads per process BASE_PORT=3035 # the first port used # you need to make the PIDFILE dir and insure it has the right permissions PIDFILE="/var/run/cherrypy/myproject.pid" WORKDIR=`dirname "$0"` cd "$WORKDIR" cp_start_proc() { N=$1 P=$(( $BASE_PORT + $N - 1 )) ./manage.py runcpserver daemonize=1 port=$P pidfile="$PIDFILE-$N" threads=$THREADS request_queue_size=0 verbose=0 } cp_start() { for N in `seq 1 $PROCESSES`; do cp_start_proc $N done } cp_stop_proc() { N=$1 #[ -f "$PIDFILE-$N" ] && kill `cat "$PIDFILE-$N"` [ -f "$PIDFILE-$N" ] && ./manage.py runcpserver pidfile="$PIDFILE-$N" stop rm -f "$PIDFILE-$N" } cp_stop() { for N in `seq 1 $PROCESSES`; do cp_stop_proc $N done } cp_restart_proc() { N=$1 cp_stop_proc $N #sleep 1 cp_start_proc $N } cp_restart() { for N in `seq 1 $PROCESSES`; do cp_restart_proc $N done } case "$1" in "start") cp_start ;; "stop") cp_stop ;; "restart") cp_restart ;; *) "$@" ;; esac 

bash脚本,我们基本上可以做3件事情:

  1. 通过调用./cherrypy_server.sh start cherrypy服务器
  2. 通过调用./cherrypy_server.sh stop cherrypy服务器
  3. 通过调用./cherrypy_server.sh restart cherrypy服务器

我怎么把这个shell脚本放在systemd的控制下作为一个cherrypy.service文件(当systemd在一台机器重新启动时启动cherrypy服务器这个明显的目标)?

参考systemd服务文件的例子 – https://wiki.archlinux.org/index.php/Systemd#Using_service_file

我用那些病毒胡子和SabNZBd,两个python/樱桃应用程序。 不同的是知道何时使用“分叉”。 这基本上告诉systemd主要的二进制文件将fork的东西,所以它必须猜测从一个文件的PID。 WantedBy只是定义需要启动的目标,将其视为运行级别。 您还会注意到,第二个定义使用一个目录来保存运行信息,这是因为它为每个启动的守护进程创build了一个$process-$port (可能会有不同的端口上的主进程产生许多守护进程)。

海事组织你可以添加脚本ExecStart,并确保它是forking和添加一种方式,以find主要的PIDfile,或至less一个PIDfile,意思是“如果这是死的,重新启动服务”。

也许最理想的是为每个守护进程创build一个“简单”的服务文件?

 [Unit] Description=Internet PVR for your TV Shows After=cryptsetup.target [Service] ExecStart=/usr/bin/python2 /path/to/Sick-Beard/SickBeard.py Type=simple User=<user under which to run> Group=<group of said user> [Install] WantedBy=multi-user.target 

这是一个分叉

 [Unit] Description=Binary Newsreader After=cryptsetup.target [Service] ExecStart=/usr/bin/python2 /path/to/sabnzbd/SABnzbd.py -d -f /path/to/inifile --pid /run/sabnzbd Type=forking PIDFile=/run/sabnzbd/sabnzbd-8080.pid User=<user to run the process> Group=<group of said user> [Install] WantedBy=multi-user.target