シェルスクリプトでデーモンを作る
デーモンって言ってもモドキだけど。
デーモンってたしか
- 制御端末を持たない
- 親プロセスが1(initの子プロセスである)
が定義だったと思う。それに似たものを作る。
exe="sleep 30" pidFile=daemon.pid start(){ if pid=`status` >/dev/null ;then echo "\`$exe' is already running: $pid" exit 1 fi echo -n "Starting $exe : " nohup $exe >&- 2>&- <&- & [ $? -ne 0 ] && echo NG || echo OK pid=$! echo $pid | tee $pidFile } stop(){ if pid=`status` >/dev/null ;then echo -n "Stopping $exe: " kill -INT $pid [ $? -ne 0 ] && echo NG || echo OK exit $? fi echo "Not runnning" exit 1 } status(){ if [ -s $pidFile ];then pid=`cat $pidFile` if [ -d /proc/$pid ];then echo "$pid" return 0 fi fi echo "NG" return 1 } case "$1" in start) start ;; stop) stop ;; status) status ;; *) echo "Usage: $0 {start|stop|status}" exit 1 esac
nohup
で起動して、さらに標準出力、標準エラー、標準入力を閉じる。
起動シェルは子プロセスが終了する前に終了するので、子プロセスはinitの子となる。が、psコマンドで見ると分かるけど端末の閉じ方が分からない。Cでいうところのsetsid
ってどうやるんだろう...?
まあでも、出入力は閉じているはずだし、nohup起動だから大丈夫ではないかと思う。
詳しい人がいたら採点お願いします。