【发布时间】:2019-05-04 14:38:11
【问题描述】:
我正在处理一个遗留 (Java 6/7) 项目,该项目使用 ProcessBuilder 以与操作系统无关的方式从机器请求 UUID。我想使用Java 8 中的Process.waitFor(long timeout, TimeUnit unit) 方法,但这在Java 6 中没有实现。相反,我可以使用waitFor(),它会阻塞直到完成或出错。
如果可能,我希望避免将使用的 Java 版本升级到 8,因为这需要进行许多其他更改(例如,将代码从已删除的内部 API 中迁移出来并升级生产 Tomcat 服务器)。
我怎样才能最好地实现执行进程的代码,并超时?我正在考虑以某种方式实施一个计划来检查进程是否仍在运行,如果是,则取消/销毁它并且已达到超时。
我当前的 (Java 8) 代码如下所示:
/** USE WMIC on Windows */
private static String getSystemProductUUID() {
String uuid = null;
String line;
List<String> cmd = new ArrayList<String>() {{
add("WMIC.exe"); add("csproduct"); add("get"); add("UUID");
}};
BufferedReader br = null;
Process p = null;
SimpleLogger.debug("Attempting to retrieve Windows System UUID through WMIC ...");
try {
ProcessBuilder pb = new ProcessBuilder().directory(getExecDir());
p = pb.command(cmd).start();
if (!p.waitFor(TIMEOUT, SECONDS)) { // No timeout in Java 6
throw new IOException("Timeout reached while waiting for UUID from WMIC!");
}
br = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = br.readLine()) != null) {
if (null != line) {
line = line.replace("\t", "").replace(" ", "");
if (!line.isEmpty() && !line.equalsIgnoreCase("UUID")) {
uuid = line.replace("-", "");
}
}
}
} catch (IOException | InterruptedException ex) {
uuid = null;
SimpleLogger.error(
"Failed to retrieve machine UUID from WMIC!" + SimpleLogger.getPrependedStackTrace(ex)
);
// ex.printStackTrace(System.err);
} finally {
if (null != br) {
try {
br.close();
} catch (IOException ex) {
SimpleLogger.warn(
"Failed to close buffered reader while retrieving machine UUID!"
);
}
if (null != p) {
p.destroy();
}
}
}
return uuid;
}
【问题讨论】:
标签: processbuilder java-6