我需要在(Red Hat 6.4)Linux中运行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..");
}
}
}
我震惊了,把它放在这个位置:/ 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
问题是“服务配置”对话框中的状态不正确。例如,在此屏幕截图中,我点击了“停止按钮”,它仍然显示为“已插入”。
我错过了哪一块拼图?