可以通过GuardServer实现,具体代码如下
1 public class GuardServer {2 private String servername
3
4 public GuardServer(String servername) {
5 this.servername = servername
6 }
7
8 public void startServer(String cmd) throws Exception {
9 System.out.println("Start Server : " + cmd)
10 //将命令分开
11 // String[] cmds = cmd.split(" ")
12 // ProcessBuilder builder = new ProcessBuilder(cmds)
13
14 //
15 ProcessBuilder builder=new ProcessBuilder(new String[]{"/bin/sh","-c",cmd})
16 //将服务器程序的输出定位到/dev/tty
17 builder.redirectOutput(new File("/dev/tty"))
18 builder.redirectError(new File("/dev/tty"))
19 builder.start() // throws IOException
20 Thread.sleep(10000)
21 }
22
23 /**
24 * 检测服务是否存在
25 *
26 * @return 返回配置的java程序的pid
27 * @return pid >0 返回的是 pid <=0 代表指定java程序未运行
28 * **/
29 public int checkServer() throws Exception {
30 int pid = -1
31 Process process = null
32 BufferedReader reader = null
33 process = Runtime.getRuntime().exec("jps -l")
34 reader = new BufferedReader(new InputStreamReader(process.getInputStream()))
35 String line
36 while ((line = reader.readLine()) != null) {
37 String[] strings = line.split("\\s{1,}")
38 if (strings.length < 2)
39 continue
40 if (strings[1].contains(servername)) {
41 pid = Integer.parseInt(strings[0])
42 break
43 }
44 }
45 reader.close()
46 process.destroy()
47 return pid
48 }
49 }
这个实际上就是执行某一段程序(不停的循环执行)。举例:File f = new File("/home/xieping/job.log")//要守护的进程文件和路径
if (!f.exists()) {//如果守护的文件不存在了,直接重新创建一个
try {
f.createNewFile()
} catch (IOException e) {
e.printStackTrace()
}
}
while (true) {//一直执行这个循环
try {
BufferedWriter output = new BufferedWriter(new FileWriter(f))
output.write(new Date().toString())//写入需要的内容
output.close()
} catch (IOException e1) {
e1.printStackTrace()
}
try {
Thread.sleep(1000 * 5)//定义循环的时间间隔是5秒
} catch (InterruptedException e) {
e.printStackTrace()
}
}
备注:通过main方法调用上面的代码,然后运行起来,不要停止这个程序,守护进程的创建就算完成了。