编写Linux服务

最近需要把ipython notebook装到服务器上,但是每次ssh去手动打开太麻烦了。而且如果ssh客户端断开了,notebook也就自己关了,这对我们一个模型需要跑半个月的人们来说是不可接受的。

然后早上花了一个小时时间,照着教程终于把ipython notebook做成linux服务了。这样就算是ssh客户端断开了,notebook也能在后台独立运行。至于是否能开机自启动,由于服务器重启速度太慢了,所以我还没测试过。。。

下面就是这个服务程序,贴出来备忘:

文件:/etc/init.d/ipythonserver

# ipython notebook 的服务
# created by Friskit

DAEMON=/usr/bin/ipython  
WORKSPACE=/home/alzhu/IPython_Workspace  #给IPython指定一个工作区  
NAME=ipserver  
PIDFILE=/var/run/$NAME.pid  
DESC="IPython Notebook Server"

ipserver_start() {  
    if \     # 使用start-stop-daemon来创建后台进程。这里需要注意的是,需要引入一大堆环境变量才能在IPython中使用Theano等等的库
        CUDA_ROOT=/usr/local/cuda/bin \
        THEANO_FLAGS=floatX=float32,device=gpu \
        PATH=$PATH:$CUDA_ROOT \
        LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda-6.5/lib64:/usr/local/cuda-6.5/lib \
        start-stop-daemon --start --quiet --background --chuid alzhu --user alzhu \
        --chdir $WORKSPACE --pidfile $PIDFILE --make-pidfile \
        --exec $DAEMON -- notebook --profile=ipserver


    then
        rc=0
        sleep 1
        if ! kill -0 $(cat $PIDFILE) >/dev/null 2>&1; then
            echo "IPython Notebook Server daemon failed to start"
            rc=1
        fi
    else
        rc=1
    fi
    if [ $rc -eq 0 ]; then
        echo "IPython Notebook Server started"
    else
        rm -f $PIDFILE
    fi
} # ipserver_start

case "$1" in  
    start)
        echo "IPython Notebook Server starting"
        if [ -s $PIDFILE ] && kill -0 $(cat $PIDFILE) >/dev/null 2>&1; then
            echo "IPython Notebook Server already running"
            exit 0
        fi
        ipserver_start
        ;;

    stop)
        echo "IPython Notebook Server stopping"
        start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
        rm -f $PIDFILE
        ;;

    reload|force-reload)
        echo "Ipython Notebook Server daemon: not needed, as the daemon"
        ;;

    restart)
        set +e
        if [ -s $PIDFILE ] && kill -0 $(cat $PIDFILE) >/dev/null 2>&1; then
            start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE || true
            sleep 1
        else
            echo "IPython Notebook Server daemon not running, attempting to start."
            rm -f $PIDFILE
       fi
       ipserver_start
       ;;

    status)
        status_of_proc -p $PIDFILE "$DAEMON" ipython
        exit $?
        ;;

    *)
        echo "Usage: /etc/init.d/ipythonserver {start|stop|reload|force-reload|restart|status}"
        exit 1
esac

exit 0  

Friskit

继续阅读此作者的更多文章