我需要在(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
问题是“服务配置”对话框中的状态不正确。例如,在这个截图中,我点击了“停止按钮”,它仍然显示为“插入”。
我错过了哪一块拼图?