記事一覧はこちら

シンプルイズベストならbashのrcスクリプト

以前同じ題材のスクリプトを書いたが、作りなおしたので投稿。 流石にpid無しは無いので、pidを/var/run/スクリプト名.pid に保存するようにしました。改善点としては、commandの記述をミスって起動に失敗したらそれが分かるようにしたい。しかし標準エラー出力もカスタム出来る事は必要だし、困った。起動後1秒間はコンソールにも出力したいんだがそういうの出来るのかな。

環境はさくらvps cent os6

#!/bin/sh
# chkconfig: 345 70 30
# description: Fushihara Twitter Log
# utf-8 and LF
command="/usr/bin/java -Dfile.encoding=UTF-8 -Xbootclasspath/a:lib/mongo-java-driver-2.11.4.jar -classpath bin com.x0.fushi.vps.twitterlog.v2.Main"
currentDirectory=/root/twitterLog/code/v2/
outStd=/root/twitterLog/javaLog.txt
outErr=/root/twitterLog/javaLog.txt

NAME=`basename $0`
pidfile="/var/run/${NAME}.pid"

if [ -z ${outStd} ]; then
    outStd=/dev/null
fi
if [ -z ${outErr} ]; then
    outErr=/dev/null
fi

start(){
    if [ -e "$pidfile" ]; then
        currentPid=`cat $pidfile`
        echo "${NAME} is already running. pid=${currentPid}"
    else
        cd ${currentDirectory}
        ${command}  >> ${outStd} 2>> ${outErr}  < /dev/null &
        mypid=$!
        echo ${mypid} > ${pidfile}
        echo "${NAME} start. pid=${mypid}"
    fi
}
stop(){
    if [ -e "$pidfile" ]; then
        currentPid=`cat $pidfile`
        `kill ${currentPid}`
        `rm -f $pidfile`
    else
        echo "${NAME} is not running."
    fi
}
status(){
    if [ ! -f "$pidfile" ]; then
        echo "${NAME} is not running."
        return
    fi
    currentPid=`cat $pidfile`
    if kill -0 $currentPid 2>> /dev/null ; then
        echo "${NAME} is running.pid=${currentPid}"
    else
        echo "${NAME} is not running."
        `rm -f $pidfile`
    fi
}

case "$1" in
     start)
          start
          ;;
     stop)
          stop
          ;;
     status)
          status
          ;;
     restart)
          stop
          start
          ;;
     *)
     echo $"Usage: ${prog} {start|stop|status|restart}: "
     RETVAL=2
esac

exit $RETVAL