在 Linux 中将 Java 进程作为服务运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17069543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running Java process as Service in Linux
提问by mainstringargs
I need to run a Java process as a service in (Red Hat 6.4) Linux (It needs to run at boot time and stay up). I have it mostly working, except for it doesn't seem to status correctly in the "Service Configuration" window.
我需要在 (Red Hat 6.4) Linux 中将 Java 进程作为服务运行(它需要在启动时运行并保持运行)。除了在“服务配置”窗口中它的状态似乎不正确之外,我大部分时间都在工作。
To illustrate, I made a simple Java program:
为了说明,我做了一个简单的Java程序:
package service;
public class JavaService {
public static void main(String args[]){
System.out.println("Starting Java-Service");
while(true){
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Java-Service is still running..");
}
}
}
I jarred that up, and put it at this location: /opt/service/lib
我把它弄乱了,把它放在这个位置:/opt/service/lib
Then, I created this script: /opt/service/bin/run_java_service
然后,我创建了这个脚本:/opt/service/bin/run_java_service
#!/bin/tcsh
#
# chkconfig: 2345 80 30
# description: java-service Service
setenv JAVA_SERVICE_HOME /opt/service
setenv CLASSPATH $JAVA_SERVICE_HOME/lib/JavaService.jar
setenv SERVICE_PID `ps aux | grep JavaService | grep -v grep | awk '{print }'`;
if ( (stop == || restart == )) then
echo "java-service stop";
kill -9 $SERVICE_PID
setenv SERVICE_PID
endif
if ( start == || restart == ) then
if($SERVICE_PID) then
echo "java-service is already running"
else
echo "java-service start";
java service.JavaService&
endif
endif
if (status == ) then
if($SERVICE_PID) then
echo "java-service (pid $SERVICE_PID) is running...";
else
echo "java-service is stopped";
endif
endif
I then created a symlink to this in the /etc/rc.d/init.d directory and added it to the chkconfig:
然后我在 /etc/rc.d/init.d 目录中创建了一个符号链接,并将其添加到 chkconfig:
sudo ln –s /opt/service/bin/run_java_service /etc/rc.d/init.d/java-service
sudo chkconfig --add java-service
At this point, commands like this work as expected from the command line:
此时,像这样的命令在命令行中按预期工作:
sudo service java-service stop
sudo service java-service start
sudo service java-service status
The problem is that things aren't statusing correctly in the "Service Configuration" dialog. For instance, in this screenshot, I have clicked the "Stop Button" and it still shows as "plugged in".
问题是“服务配置”对话框中的状态不正确。例如,在此屏幕截图中,我单击了“停止按钮”,但它仍显示为“已插入”。
What piece of the puzzle am I missing?
我错过了什么拼图?