start-stop-daemon 是 Debian 家族的守護行程管理工具,能指定以哪個使用者身分啟動或停止服務。RedHat 系沒有預附,需要自行編譯 dpkg 取得。
線上手冊:https://man7.org/linux/man-pages/man8/start-stop-daemon.8.html。
wget https://ftp.de.debian.org/debian/pool/main/d/dpkg/dpkg_1.16.18.tar.xz
tar -xf dpkg_1.16.18.tar.xz && cd dpkg_1.16.18
./configure
若出現 configure: error: no curses library found,補上 ncurses 開發套件再重跑:
yum install ncurses-devel -y
./configure && make
find / -name start-stop-daemon # 找出編譯出來的位置
把可執行檔複製到 PATH 裡,之後就能寫成服務腳本:
cp /usr/local/src/dpkg-1.16.18/utils/start-stop-daemon /usr/local/sbin/
以下以 Jenkins 為例,做出一支可用 start/stop/restart 控制的腳本:
#!/bin/sh
DESC="Jenkins CI Server"
NAME=jenkins
PIDFILE=/var/run/$NAME.pid
RUN_AS=jenkins
COMMAND="/usr/bin/java -- -jar /home/jenkins/jenkins.war"
d_start() {
start-stop-daemon --start --quiet --background --make-pidfile \
--pidfile $PIDFILE --chuid $RUN_AS --exec $COMMAND
}
d_stop() {
start-stop-daemon --stop --quiet --pidfile $PIDFILE
[ -e $PIDFILE ] && rm $PIDFILE
}
case $1 in
start) echo -n "Starting $DESC: $NAME"; d_start; echo "." ;;
stop) echo -n "Stopping $DESC: $NAME"; d_stop; echo "." ;;
restart) echo -n "Restarting $DESC: $NAME"; d_stop; sleep 1; d_start; echo "." ;;
*) echo "usage: $NAME {start|stop|restart}"; exit 1 ;;
esac
exit 0
關鍵參數是 --chuid(指定執行身分)、--background(放背景)與 --make-pidfile(自動寫 pid 檔),這幾個一齊用,就不必自己 fork 與記錄程序號。