How to convert an existing Java application to a SYS V service (daemon) [duplicate]
Asked Answered
C

2

8

I have a Java application, to start it I use

java -jar myapp.jar

To stop it I use CTRL+C.

Now I need to convert that application to something that I can start with:

/etc/init.d/myapp start

And I can stop with:

/etc/init.d/myapp stop

The problem is all about saving the PID of the process, I think I saw somewhere a recipe for doing this, I don't remember where and I'm not able to find it.

I saw that there is a project called Java Server Wrapper, but I look for something free that does not limit memory usage. And I think that this work could be done in a single bash script.

Cassis answered 2/1, 2009 at 15:8 Comment(3)
What do you mean by "does not limit memory usage"? Sun's JVM memory usage is always limited (if you do not specify -Xmx, there is a default value).Effective
@alex, Maybe I did not understood correctly this page wrapper.tanukisoftware.org/doc/english/…Cassis
Andrea: Sun JVM always have some memory limit. If you don't set it explicitely, it is 64m. As 64m is not much, you usually always want to change this value yourself. It seems that Java Service Wrapper can set this limit using percentage, and not just absolute value, as is the usual case.Foraminifer
R
11

Take a look at Apache Commons Daemon.

It has 'jsvc' launcher which suports starting and stopping java-based daemons (services).

Redhead answered 2/1, 2009 at 15:18 Comment(0)
A
8

Firstly, Saving the PID on *nix:

$ ./yourprogram &
$ echo $! > /var/run/yourpid

yourpid will now contain yourpgram's PID, and /var/run is the proper place to put it.

The above can be put in your "start" script. The "stop" script can look at yourpid to know what to kill.

If you want to be more elegant and stop your app properly, you can look at the source code for Tomcat's org.apache.catalina.startup.Catalina.java on how to implement proper shutdown hooks.

Secondly, above "stop" and "start" scripts can then be put in /etc/init.d/mystopstartscript:

#!/bin/bash
# processname: yourprogram
# pidfile: /var/run/yourpid

case $1 in
start)
        sh /some/where/start.sh
        ;;
stop)  
        sh /some/where/stop.sh
        ;;
restart)
        sh /some/where/stop.sh
        sh /some/where/start.sh
        ;;
esac   
exit 0

This is a fairly home-grown solution, with ideas mostly taken from good 'ol Tomcat, but I hope it helps :)

Abacus answered 5/1, 2009 at 2:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.