java应用程序的Linux启动脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7577620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 06:23:38  来源:igfitidea点击:

Linux start-up script for java application

javalinuxubuntustartupredhat

提问by Joe Ijam

I have Jar file to run in Linux using this command:

我有 Jar 文件可以使用以下命令在 Linux 中运行:

java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13

Can anyone let me know how to create script and implement this process automatically while we restart our computer? In windows we use services but how about linux? Can u provide to me the script and step to do that since i am really new in Linux...

任何人都可以让我知道如何在我们重新启动计算机时创建脚本并自动执行此过程吗?在 Windows 中我们使用服务,但 linux 怎么样?你能向我提供脚本和步骤吗,因为我真的是 Linux 新手...

Linux : RHat, Ubuntu

Linux : RHat, Ubuntu

Thanks

谢谢

采纳答案by Sérgio Michels

If you want to run the app as linux daemon (service) checkout Java Wrapper: http://wrapper.tanukisoftware.com/doc/english/download.jsp

如果您想将应用程序作为 linux 守护进程(服务)运行,请查看Java Wrapper:http: //wrapper.tanukisoftware.com/doc/english/download.jsp

Check this answer too (is for windows, but for linux changes a little bit): How to install a Java application as a service

也请检查此答案(适用于 Windows,但适用于 linux):How to install a Java application as a service

回答by ask21900

While it is not recommended to sudo items like this, it can be accomplished by the following:

虽然不建议 sudo 这样的项目,但可以通过以下方式完成:

sudo crontab -e

Place the following in the cron:

将以下内容放入 cron:

@reboot java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13

回答by Aquertu

Uhh first you might want to edit out your local ip thats more information that your giving out. Anyhow just open up a new document type this

呃,首先你可能想编辑你的本地 ip,这是你提供的更多信息。无论如何,只需打开一个新文档键入此

 #!/bin/bash

 #put your commands in here

Save then open up terminal and type chmod +x nameofscript

保存然后打开终端并输入 chmod +x nameofscript

Im not sure about ubuntu but on arch we have a place to run commands on startup. My advice is to goto system->prefernces->start up applications or something along that line its in that menu I know.

我不确定 ubuntu,但在 arch 上我们有一个地方可以在启动时运行命令。我的建议是转到系统-> 首选项-> 启动应用程序或我知道的菜单中的类似内容。

Type the path to the script ie /home/username/scrips/myawesomescript

输入脚本的路径,即 /home/username/scrips/myawesomescript

回答by ott--

Basically, you need to create a little shell script in /etc/init.d and make symlinks to /etc/rc2.d and /etc/rc5.d. The contents could be like this:

基本上,您需要在 /etc/init.d 中创建一个小 shell 脚本,并创建指向 /etc/rc2.d 和 /etc/rc5.d 的符号链接。内容可能是这样的:

#!/bin/sh
if [ "" = start ] ; then
    cd /put_your_workdir_here
    /usr/bin/java -jar SyslogAgent_01.jar 192.168.2.154 1998 D:/apachelog.log ApacheLog 13 &
fi

Notice that you start your program in background (& at the end of the commandline)

请注意,您在后台启动程序(& 在命令行的末尾)

回答by Anupam Saini

you need to create a unix shell script file, that will automate the job for you. Here are the steps to create the script file: http://www.linuxquestions.org/questions/linux-general-1/shell-script-for-jar-utility-769461/

您需要创建一个 unix shell 脚本文件,它将为您自动完成工作。以下是创建脚本文件的步骤:http: //www.linuxquestions.org/questions/linux-general-1/shell-script-for-jar-utility-769461/

回答by SSpoke

I would start with this template for a startup script rename the SCRIPT_HOMEto proper path and call this file without any extensions, then in SSH run this command.

我将从这个启动脚本的模板开始,将其重命名SCRIPT_HOME为正确的路径,并在没有任何扩展名的情况下调用此文件,然后在 SSH 中运行此命令。

chkconfig –add javaserver

Note the javaserverin the chkconfigis how you called the file below, (no extensions or it wont work).

请注意,javaserverchkconfig你是怎么叫下面的文件,(不支持分机或它不会工作)。

#!/bin/bash
#
# javaserver: Startup script for Any Server Application.
#
# chkconfig: 35 80 05
# description: Startup script for Any Server Application.

SCRIPT_HOME=/var/java_server;
export SCRIPT_HOME

start() {
        echo -n "Starting Java Server: "
        $SCRIPT_HOME/run.sh start
        sleep 2
        echo "done"
}

stop() {
        echo -n "Stopping Java Server: "
        $SCRIPT_HOME/run.sh stop
        echo "done"
}

# See how we were called.
case "" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        restart)
                stop
                start
                ;;
        *)
                echo $"Usage: javaserver {start|stop|restart}"
                exit
esac

Now here is the script the run.sh (this can be used instead of the template but I find it easier to make the template script small and unchangeable link to my main script so I never have to touch it again.

现在这里是 run.sh 的脚本(它可以用来代替模板,但我发现使模板脚本更小并且与我的主脚本的不可更改的链接更容易,所以我再也不必碰它了。

The script below is one of a very few scripts I found that actually can restart a java program without turning off all the java programs you currently have running, this one only targets the program it opened in the first place so it will never make any mistakes, never had it fail on me, run on user rootno problem.
Runs your program in the background forever too (no need to keep SSH opened).

下面的脚本是我发现的少数几个脚本之一,它实际上可以在不关闭您当前运行的所有 Java 程序的情况下重新启动 Java 程序,这个脚本只针对它首先打开的程序,因此它永远不会出错,从来没有在我身上失败过,在用户上运行root没问题。
也永远在后台运行您的程序(无需保持 SSH 打开)。

This is the run.sh

这是 run.sh

#!/bin/bash
#
# chkconfig: 345 99 05 
# description: Java deamon script
#
# A non-SUSE Linux start/stop script for Java daemons.
#
# Set this to your Java installation
JAVA_HOME=/usr/bin/

scriptFile=$(readlink -fn $(type -p ##代码##))                                        # the absolute, dereferenced path of this script file
scriptDir=$(dirname $scriptFile)                                                    # absolute path of the script directory
serviceNameLo="javaserver"                                                       # service name with the first letter in lowercase
serviceName="JavaServer"                                                           # service name
serviceUser="root"                                                                           # OS user name for the service
serviceGroup="root"                                                                         # OS group name for the service
applDir="/var/java_server"                                       # home directory of the service application
serviceUserHome="/home/$serviceUser"                                      # home directory of the service user
serviceLogFile="/var/log/$serviceNameLo.log"                            # log file for StdOut/StdErr
maxShutdownTime=15                                                                     # maximum number of seconds to wait for the daemon to terminate normally
pidFile="/var/run/$serviceNameLo.pid"                                        # name of PID file (PID = process ID number)
javaCommand="java"                                                                       # name of the Java launcher without the path
javaArgs="MyJavaAppClass"                                                                  # arguments for Java launcher
javaCommandLine="$JAVA_HOME$javaCommand $javaArgs"   # command line to start the Java service application
javaCommandLineKeyword="MyJavaAppClass"                                   # a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others

# Makes the file  writable by the group $serviceGroup.
function makeFileWritable {
   local filename=""
   touch $filename || return 1
   chgrp $serviceGroup $filename || return 1
   chmod g+w $filename || return 1
   return 0; }

# Returns 0 if the process with PID  is running.
function checkProcessIsRunning {
   local pid=""
   if [ -z "$pid" -o "$pid" == " " ]; then return 1; fi
   if [ ! -e /proc/$pid ]; then return 1; fi
   return 0; }

# Returns 0 if the process with PID  is our Java service process.
function checkProcessIsOurService {
   local pid=""
   if [ "$(ps -p $pid --no-headers -o comm)" != "$javaCommand" ]; then return 1; fi
   grep -q --binary -F "$javaCommandLineKeyword" /proc/$pid/cmdline
   if [ $? -ne 0 ]; then return 1; fi
   return 0; }

# Returns 0 when the service is running and sets the variable $pid to the PID.
function getServicePID {
   if [ ! -f $pidFile ]; then return 1; fi
   pid="$(<$pidFile)"
   checkProcessIsRunning $pid || return 1
   checkProcessIsOurService $pid || return 1
   return 0; }

function startServiceProcess {
   cd $applDir || return 1
   rm -f $pidFile
   makeFileWritable $pidFile || return 1
   makeFileWritable $serviceLogFile || return 1
   cmd="nohup $javaCommandLine >>$serviceLogFile 2>&1 & echo $! >$pidFile"
   # Don't forget to add -H so the HOME environment variable will be set correctly.
   #sudo -u $serviceUser -H $SHELL -c "$cmd" || return 1
   su --session-command="$javaCommandLine >>$serviceLogFile 2>&1 & echo $! >$pidFile" $serviceUser || return 1
   sleep 0.1
   pid="$(<$pidFile)"
   if checkProcessIsRunning $pid; then :; else
      echo -ne "\n$serviceName start failed, see logfile."
      return 1
   fi
   return 0; }

function stopServiceProcess {
   kill $pid || return 1
   for ((i=0; i<maxShutdownTime*10; i++)); do
      checkProcessIsRunning $pid
      if [ $? -ne 0 ]; then
         rm -f $pidFile
         return 0
         fi
      sleep 0.1
      done
   echo -e "\n$serviceName did not terminate within $maxShutdownTime seconds, sending SIGKILL..."
   kill -s KILL $pid || return 1
   local killWaitTime=15
   for ((i=0; i<killWaitTime*10; i++)); do
      checkProcessIsRunning $pid
      if [ $? -ne 0 ]; then
         rm -f $pidFile
         return 0
         fi
      sleep 0.1
      done
   echo "Error: $serviceName could not be stopped within $maxShutdownTime+$killWaitTime seconds!"
   return 1; }

function startService {
   getServicePID
   if [ $? -eq 0 ]; then echo -n "$serviceName is already running"; RETVAL=0; return 0; fi
   echo -n "Starting $serviceName   "
   startServiceProcess
   if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
   echo "started PID=$pid"
   RETVAL=0
   return 0; }

function stopService {
   getServicePID
   if [ $? -ne 0 ]; then echo -n "$serviceName is not running"; RETVAL=0; echo ""; return 0; fi
   echo -n "Stopping $serviceName   "
   stopServiceProcess
   if [ $? -ne 0 ]; then RETVAL=1; echo "failed"; return 1; fi
   echo "stopped PID=$pid"
   RETVAL=0
   return 0; }

function checkServiceStatus {
   echo -n "Checking for $serviceName:   "
   if getServicePID; then
    echo "running PID=$pid"
    RETVAL=0
   else
    echo "stopped"
    RETVAL=3
   fi
   return 0; }

function main {
   RETVAL=0
   case "" in
      start)                                               # starts the Java program as a Linux service
         startService
         ;;
      stop)                                                # stops the Java program service
         stopService
         ;;
      restart)                                             # stops and restarts the service
         stopService && startService
         ;;
      status)                                              # displays the service status
         checkServiceStatus
         ;;
      *)
         echo "Usage: ##代码## {start|stop|restart|status}"
         exit 1
         ;;
      esac
   exit $RETVAL
}

main