我需要在Linux(Red Hat 6.4)上将Java进程作为服务运行(需要在启动时运行并保持运行)。我已经基本实现了这一点,但它似乎无法在“服务配置”窗口中正确地显示状态。
为了举例说明,我创建了一个简单的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..");
}
}
}
我将其打成了jar包,并放置在此位置:/opt/service/lib。
然后,我创建了这个脚本:/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 $2}'`;
if ( (stop == $1 || restart == $1)) then
echo "java-service stop";
kill -9 $SERVICE_PID
setenv SERVICE_PID
endif
if ( start == $1 || restart == $1 ) then
if($SERVICE_PID) then
echo "java-service is already running"
else
echo "java-service start";
java service.JavaService&
endif
endif
if (status == $1) then
if($SERVICE_PID) then
echo "java-service (pid $SERVICE_PID) is running...";
else
echo "java-service is stopped";
endif
endif
我随后在 /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
此时,像这样的命令可以从命令行中正常工作:
sudo service java-service stop
sudo service java-service start
sudo service java-service status
问题在于“服务配置”对话框中的状态不正确。例如,在此截图中,我已单击“停止按钮”,但它仍显示为“已连接”。你缺少了哪个重要的部分?