Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 485
Andrea Francia Avatar asked Jan 02 '09 15:01

Andrea Francia


2 Answers

Take a look at Apache Commons Daemon.

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

like image 129
Peter Štibraný Avatar answered Oct 16 '22 18:10

Peter Štibraný


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 :)

like image 31
opyate Avatar answered Oct 16 '22 20:10

opyate