LoginSignup
14
14

More than 5 years have passed since last update.

標準出力にログを吐くアプリケーションのデーモンを start-stop-daemon で立てる

Posted at

GrowthForecast には残念ながらログファイルを書き出すオプションは無く,すべて標準出力に吐くようです

しかしそのようなアプリケーションでも start-stop-daemon を使って daemon 化してかつ標準出力に吐くログをログファイルとして保存したいことがあります

このような場合ただリダイレクトするだけではうまくいかないので以下のようにします

start-stop-daemon --start --background --exec "/bin/bash" --make-pidfile --pidfile "$PID" -- \
  -c "exec $DAEMON >> /var/tmp.log 2>&1"

まず bash の daemon として立ち上げますが,このままだと bash が daemon として起動してしまいます
そうなると pid が bash の daemon となり肝心の立ち上げたいプロセスの管理ができなくなってしまいます

そこで bash の exec を使います

これを使えば標準出力をログファイルに書き出せてかつ pid も管理したいプロセスのものになります

今回は GrowthForecast を実行する専用ユーザー gf を作成してそこで plenv を使って Perl と GrowthForecast をインストールしたので以下の様なスクリプトを用意しました

gf
#!/bin/bash

PATH=/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin

APP=growthforecast
ROOT_DIR="/home/gf"
DATA_DIR="${ROOT_DIR}/data"
PID="${ROOT_DIR}/gf.pid"
NAME=growthforecast
DAEMON="/home/gf/.plenv/shims/growthforecast.pl"
DAEMON_USER="gf"

. /lib/lsb/init-functions

case "$1" in
  start)
    echo "start $NAME";
    start-stop-daemon --start --chuid "$DAEMON_USER" --background --exec "/bin/bash" --make-pidfile --pidfile "$PID" -- \
      -c "exec $DAEMON --data-dir /home/gf/data --front-proxy=127.0.0.1 --enable-float-number >> /home/gf/log/gf.log 2>&1"
    ;;
  stop)
    log_daemon_msg "Stopping " "$NAME"
    start-stop-daemon --stop --oknodo --signal TERM --pidfile "$PID"
    log_end_msg $?
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
    echo "Usage: gf {start|stop|restart}"
    exit 1
    ;;
esac

exit 0
14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14