最近默默地进入了两三个项目组,其中一个是关于ICE服务的项目。关于ICE分布式架构网上有很多资料,这里就不详述了。好不容易搞完ICE的几个接口,由于做项目产品化的缺人,只好由我来继续搞ICE服务端的产品化相关工作。其中一个需求就是需要一个看门狗(守护进程)来“看着”ICE服务进程,该服务进程是在windows系统下跑的,这里就需要Java来调用Windows下批处理的一些命令。
下面的代码和真正的项目代码有些出入,因为原项目代码会有相关公司的信息。这里采用 http://blog.csdn.net/fenglibing/article/details/6372444 博主写的ICE程序示例,针对该博客的服务端程序的看门狗。
public class ServerDeamon {
public static void main(String[] args) {
int status = 0;
Ice.Communicator ic = null;
try {
//初始化
ic = Ice.Util.initialize(args);
//传入远程服务单元的名称、网络协议、IP及端口,获取Printer的远程代理,这里使用的stringToProxy方式
Ice.ObjectPrx base = ic.stringToProxy("SimplePrinter:default -p 10000");
//看门狗开始看门,没有吃到东西的话每隔十秒就会狂吠
while (true) {
try {
//通过checkedCast向下转换,获取Printer接口的远程,并同时检测根据传入的名称获取的服务单元是否Printer的代理接口,如果不是则返回null对象,
Demo.PrinterPrx printer = Demo.PrinterPrxHelper.checkedCast(base);
if (printer == null){
//此时看门狗没有吃到东西,开始狂吠
System.out.println("connect ICE filed");
Deamon();
}
}catch (Exception e){
e.printStackTrace();
Deamon();
}
Thread.sleep(10000);
}
}catch (Exception e){
e.printStackTrace();
} finally{
if(ic != null){
ic.destroy();
}
}
}
public static void Deamon(){
try {
String commond = "cmd.exe /c call C:\\deom.exe";
System.out.println(commond);
//使用Runtime.getRuntime().exec()执行批处理命令
Process pro = Runtime.getRuntime().exec("cmd.exe /c tasklist | find \"EightLibServer.exe\" ");
BufferedReader reader=new BufferedReader(new InputStreamReader(pro.getInputStream()));
String str=reader.readLine();
if (str!=null)
{
System.out.println( "deom.exe出错,但正在运行,尝试重启... ");
Runtime.getRuntime().exec("cmd.exe /c taskkill /f /t /im EightLibServer.exe ");
Thread.sleep(500);
Runtime.getRuntime().exec(commond);
}else{
System.out.println( "deom.exe没有在运行,尝试重启...");
Runtime.getRuntime().exec(commond);
}
reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}