废话不多说,直接上代码。
(1)自定义看门狗,如下:
import org.apache.commons.exec.ExecuteWatchdog;
import org.apache.commons.exec.Watchdog;
/**
* 自定义看门狗
* @author hxstrive.com 2021/12/26
*/
public class MyExecuteWatchdog extends ExecuteWatchdog {
public MyExecuteWatchdog(long timeout) {
super(timeout);
}
@Override
public void timeoutOccured(Watchdog w) {
super.timeoutOccured(w);
System.out.println("我自己的看门狗");
}
}(2)将自定义的看门狗通过 DefaultExecutor 的 setWatchdog() 方法设置到 Commons Exec 中,如下:
import org.apache.commons.exec.CommandLine;
import org.apache.commons.exec.DefaultExecutor;
import org.apache.commons.exec.PumpStreamHandler;
import java.io.ByteArrayOutputStream;
/**
* 自定义看门狗,通过继承 ExecuteWatchdog 实现
* @author hxstrive.com 2021/12/26
*/
public class WatchdogDemo2 {
public static void main(String[] args) throws Exception {
// 1.构建命令行
CommandLine commandLine = new CommandLine("cmd.exe");
commandLine.addArgument("/c");
commandLine.addArgument("ping");
commandLine.addArgument("www.hxstrive.com");
commandLine.addArguments(new String[]{"-n", "20"});
// 2.建立接收输出信息的流
// 接收结果流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// 接收错误信息流
ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
// 3.创建执行器
DefaultExecutor executor = new DefaultExecutor();
executor.setStreamHandler(new PumpStreamHandler(outputStream, errorStream));
// 4.创建看门狗,5秒后自动结束进程
// 进程的超时时间(以毫秒为单位),一定是大于 0 或 'INFINITE_TIMEOUT'
MyExecuteWatchdog watchdog = new MyExecuteWatchdog(5000);
executor.setWatchdog(watchdog);
// 5.执行命令
executor.execute(commandLine);
// 6.输出结果
System.out.println(outputStream.toString("GBK"));
System.out.println(errorStream.toString("GBK"));
}
}运行程序,输出如下:
我自己的看门狗 Exception in thread "main" org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1) at org.apache.commons.exec.DefaultExecutor.executeInternal(DefaultExecutor.java:404) at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:166) at org.apache.commons.exec.DefaultExecutor.execute(DefaultExecutor.java:153) at com.hxstrive.exec.watchdog.WatchdogDemo2.main(WatchdogDemo2.java:38)