How to start a Java program as a Linux daemon with an /etc/init.d script.

See also:

Here is the CentOS/RedHat/Ubuntu version of the SUSE script:

#!/bin/bash
#
# chkconfig: 345 99 05
# description: Java deamon script
#
# A non-SUSE Linux start/stop script for Java daemons.
#
# Derived from -
# Home page: http://www.source-code.biz
# License: GNU/LGPL (http://www.gnu.org/licenses/lgpl.html)
# Copyright 2006 Christian d'Heureuse, Inventec Informatik AG, Switzerland.
#
# History:
# 2010-09-21 Josh Davis: Changed 'sudo' to 'su', fix some typos, removed unused variables
# 2009-03-04 Josh Davis: Ubuntu/Redhat version.
# 2006-06-27 Christian d'Heureuse: Script created.
# 2006-07-02 chdh: Minor improvements.
# 2006-07-10 chdh: Changes for SUSE 10.0. # Set this to your Java installation
JAVA_HOME=/usr/java/latest serviceNameLo="myservice" # service name with the first letter in lowercase
serviceName="MyService" # service name
serviceUser="appuser" # OS user name for the service
serviceGroup="appgroup" # OS group name for the service
applDir="/var/lib/$serviceNameLo" # 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
javaExe="$JAVA_HOME/bin/$javaCommand" # file name of the Java application launcher executable
javaArgs="-jar $applDir/myservice.jar" # arguments for Java launcher
javaCommandLine="$javaExe $javaArgs" # command line to start the Java service application
javaCommandLineKeyword="myservice.jar" # a keyword that occurs on the commandline, used to detect an already running service process and to distinguish it from others # Makes the file $1 writable by the group $serviceGroup.
function makeFileWritable {
local filename="$1"
touch $filename || return 1
chgrp $serviceGroup $filename || return 1
chmod g+w $filename || return 1
return 0; } # Returns 0 if the process with PID $1 is running.
function checkProcessIsRunning {
local pid="$1"
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 $1 is our Java service process.
function checkProcessIsOurService {
local pid="$1"
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"
su -m $serviceUser -s $SHELL -c "$cmd" || 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 "$1" 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: $0 {start|stop|restart|status}"
exit 1
;;
esac
exit $RETVAL
} main $1

[转]Java Daemon Startup Script的更多相关文章

  1. 升级gitk后,Error in startup script: unknown color name "lime"

    $ gitkError in startup script: unknown color name "greeen" (processing "-fore" o ...

  2. Java过滤任意(script,html,style)标签符,返回纯文本--封装类

     import java.util.regex.Pattern;   /**  * 过滤标签字符串,返回纯文本  *  */ public class ChangePlainText {        ...

  3. java线程基础知识----java daemon线程

    java线程是一个运用很广泛的重点知识,我们很有必要了解java的daemon线程. 1.首先我们必须清楚的认识到java的线程分为两类: 用户线程和daemon线程 A. 用户线程: 用户线程可以简 ...

  4. JAVA DAEMON线程的理解

    java线程分两种:用户线程和daemon线程.daemon线程或进程就是守护线程或者进程,但是java中所说的daemon线程和linux中的daemon是有一点区别的. linux中的daemon ...

  5. Java Daemon 守护线程

    Java中可以通过Thread或ThreadGroup的setDaemon方法将线程设置为守护线程 当所有非守护线程退出后 守护线程将被杀死不在运行 .Net中可以通过设置IsBackground属性 ...

  6. Java daemon thread 守护线程

    守护线程与普通线程写法上基本么啥区别,在启动线程前, 调用线程对象的方法setDaemon(true),则可以将其设置为守护线程. 守护线程使用的情况较少,但并非无用,举例来说,JVM的垃圾回收.内存 ...

  7. Java菜鸟学习 Script 脚本语言(简介)

    script 可以写在head里 也可以写在body里 还可以写在 /html后面 script 也是成对出现的  <script></script> 他有三种常见的对话框 1 ...

  8. FreeBSD 10 发布

    发行注记:http://www.freebsd.org/releases/10.0R/relnotes.html 下文翻译中... 主要有安全问题修复.新的驱动与硬件支持.新的命名/选项.主要bug修 ...

  9. JAVA MemCache 史无前例的详细讲解【转】

    非原创转自:http://nhy520.iteye.com/blog/1775893 这篇文章是我看到的介绍的比较详细的,入门级别算是足足够了 Memcach什么是Memcache Memcache集 ...

随机推荐

  1. gvim & vim

    安装了 GVim for Windows. 一 普通功能配置 配置文件 _vimrc 在安装目录下面. 关闭闪屏和声音提示功能: set visualbell t_vb= "关闭visual ...

  2. bootstrap栅格布局

    <!DOCTYPE html> <html lang="en"> <head> <!-- //简介:boststrap内置了一套响应式,移 ...

  3. 开源的Android开发框架-------PowerFramework使用心得(三)内置浏览器BrowserActivity

    使用内置浏览器必须是引用源码的方式(因为jar中不能打包布局文件等资源).内置浏览器是一个继承自BaseActivity的普通Activity,使用WebView实现. 1.简单的打开内置浏览器 In ...

  4. 在Cognos报表中使用钻取特性,参数传递

    转载至:http://blog.sina.com.cn/s/blog_6eda1c4e0100mu3t.html Cognos的钻取方式大致可以分为三种: 1.模型固有的->由CUBE和DMR支 ...

  5. CXF处理Date类型的俩种方式

    1. CXF利用wsdl2java生成客户端时Date日期类型转换 http://cwfmaker.iteye.com/blog/1142835 2. GregorianCalendar cal = ...

  6. Oracle11G安装

    1.安装Oracle 记住要设置好密码 不要忘了 解锁scott(注意一定要解锁)账户, 去掉前面的绿色小勾,输入密码.同样可以输入平常用的短小的密码,不必非得按oracle建议的8位以上大小写加数字 ...

  7. zepto源码研究 - callback.js

    简要:$.Callbacks是一个生成回调管家Callback的工厂,Callback提供一系列方法来管理一个回调列表($.Callbacks的一个私有变量list),包括添加回调函数, 删除回调函数 ...

  8. 键盘数字对应的ASCII码(keycode码)

    keycode 1 = 鼠标左键keycode 2 = 鼠标右键keycode 3 = Cancelkeycode 4 = 鼠标中键keycode 8 = BackSpace keycode 9 = ...

  9. 09_linux下安装Nvidia显卡驱动

    下载驱动 去官网找去,哈哈o(^▽^)o 安装kernel source [root@localhost ~]# yum install kernel-devel 如果还不行,试试下面的 [root@ ...

  10. php中文件引入require

    ./ 表示当前层 ../表示向上一层 php中好像不能像asp那样,用 “/” 表示根目录,但可以用$_SERVER['DOCUMENT_ROOT'] 表示网站根目录 引用分为三种: 上级对下级的引用 ...