如何将现有 Java 应用程序转换为 SYS V 服务(守护程序)

发布于 2024-07-11 20:14:46 字数 524 浏览 3 评论 0原文

我有一个 Java 应用程序,为了启动它,我使用

java -jar myapp.jar

要停止它,我使用 CTRL+C。

现在我需要将该应用程序转换为我可以开始使用的东西:

/etc/init.d/myapp 启动

我可以停止:

/etc/init.d/myapp 停止

问题在于保存进程的PID,我想我在某处看到了这样做的方法,我不记得在哪里,也找不到它。

我看到有一个名为 Java Server Wrapper 的项目,但我在寻找一些东西free 不限制内存使用。 我认为这项工作可以在单个 bash 脚本中完成。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

执笔绘流年 2024-07-18 20:14:46

查看 Apache Commons 守护进程

它有“jsvc”启动器,支持启动和停止基于 java 的守护进程(服务)。

Take a look at Apache Commons Daemon.

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

习惯成性 2024-07-18 20:14:46

首先,将 PID 保存在 *nix 上:

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

yourpid 现在将包含您的程序的 PID,而 /var/run 是放置它的正确位置。

上面的内容可以放入您的“启动”脚本中。
“停止”脚本可以查看你的pid以知道要杀死什么。

如果你想更优雅地正确停止你的应用程序,你可以查看 Tomcat 的 org.apache.catalina.startup.Catalina.java 的源代码,了解如何实现正确的关闭挂钩。

其次,上面的“停止”和“启动”脚本可以放入 /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

这是一个相当本土的解决方案,其想法主要取自优秀的 Tomcat,但我希望它有所帮助: )

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文