在Linux Ubuntu上将jar文件作为Daemon运行

Hen*_*nok 3 linux bash shell daemon jar

我想在我的Teamspeak3上安装一个bot,并在启动时将该bot作为守护进程运行.我编写了自己的脚本并将其复制到init.d,然后将其添加update-rc.d到默认值.

#!/bin/sh
#
# JTS3ServerBot Script
#
USER="ts"
NAME="jts3"
DIR="/home/ts/jts3/"
case $1 in
    start)
        echo "Starting ${NAME} ..."
        if [ ! -f $DIR/pid ]; then
            sudo -u $USER -c nohup java -jar $DIR/JTS3ServerMod.jar $DIR 2>> /dev/null >> /dev/null &
            echo $! > $DIR/pid
            echo "${NAME} started ..."
        else
            echo "${NAME} is already running ..."
        fi
    ;;
    stop)
        if [ -f $DIR/pid ]; then
            PID=$(cat $DIR/pid);
            echo "Stopping ${NAME} ..."
            kill $PID;
            echo "${NAME} stopped ..."
            rm $DIR/pid
        else
            echo "${NAME} is not running ..."
        fi
    ;;
    restart)
        if [ -f $DIR/pid ]; then
            PID=$(cat $DIR/pid);
            echo "Stopping ${NAME} ...";
            kill $PID;
            echo "${NAME} stopped ...";
            rm $DIR/pid

            echo "Starting ${NAME} ..."
            sudo -u $USER -c nohup java -jar $DIR/JTS3ServerMod.jar $DIR 2>> /dev/null >> /dev/null &
            echo $! > $DIR/pid
            echo "${NAME} started ..."
        else
            echo "${NAME} is not running ..."
        fi
    ;;
esac
Run Code Online (Sandbox Code Playgroud)

生成的pid文件,但如果我尝试使用此pid终止进程,则会收到该进程不存在的错误.如果我使用的top话没有列出pid的进程.

root@vps-1023645-8462:~# service jts3 start
Starting jts3 ...
jts3 started ...
root@vps-1023645-8462:~# cat /home/ts/jts3/pid 
10206
root@vps-1023645-8462:~# kill 10206
bash: kill: (10206) - No such process

  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND           
 1762 ts        20   0 1881m  14m 3408 S    0  1.4 215:47.28 ts3server_linux    
32356 ts        20   0  164m 1576 1336 S    0  0.2   0:09.85 tsdnsserver_lin 
Run Code Online (Sandbox Code Playgroud)

Hen*_*nok 8

我找到了另一个解决我问题的方法.我使用upstart(仅适用于Ubuntu)来运行我的jar-File作为守护进程.Upstart管理PID.只需添加myservice.conf/etc/init(不/etc/inid.d)和守护程序将在启动开始,你可以mangage它作为一个服务.您不必使文件可运行或其他任何内容

例如,您可以正常管理服务

service myservice restart
service myservice status
...
Run Code Online (Sandbox Code Playgroud)

我的配置文件:

description "myservice"
author "your name"

start on runlevel [3]
stop on shutdown

expect fork

script   
    cd /home/username/
    sudo -u username java -jar /home/username/myservice/myservice.jar >/home/username/myservice.log 2>&1
    emit myservice_running
end script
Run Code Online (Sandbox Code Playgroud)

这个解决方案非常简单,在我的Ubuntu 12.04服务器上运行良好.