问题
This question already has an answer here:
- How to Daemonize a Java Program? 11 answers
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.
回答1:
Take a look at Apache Commons Daemon.
It has 'jsvc' launcher which suports starting and stopping java-based daemons (services).
回答2:
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 :)
来源:https://stackoverflow.com/questions/407016/how-to-convert-an-existing-java-application-to-a-sys-v-service-daemon