提交 25fe27c4 authored 作者: 吕本才's avatar 吕本才

fix(ProcessUtil): 修复Linux/AIX环境进程ID获取逻辑

1. 调整注释格式统一风格 2. 新增NoSuchMethodError降级处理逻辑,兼容更多JDK版本 3. 修正缩进不规范问题 4. 优化异常处理流程
上级 7d3974a1
......@@ -40,13 +40,14 @@ public class ProcessUtil {
}
} else if (Platform.isLinux() || Platform.isAIX()) {
try {
// Class<?> clazz = Class.forName("java.lang.UNIXProcess");
// field = clazz.getDeclaredField("pid");
// field.setAccessible(true);
// pid = (Integer) field.get(process);
// Class<?> clazz = Class.forName("java.lang.UNIXProcess");
// field = clazz.getDeclaredField("pid");
// field.setAccessible(true);
// pid = (Integer) field.get(process);
// 服务器上的jdk版本大于8 ,不兼容当前的模式
String processName = process.getClass().getName();
logger.info("processName: {}", processName);
if (processName.equals("java.lang.UNIXProcess")) {
try {
// 仅Java 8兼容:保留原逻辑(可选)
......@@ -54,17 +55,40 @@ public class ProcessUtil {
pidField.setAccessible(true);
pid = pidField.getLong(process);
} catch (Exception e) {
logger.error("jdk8-erro-get process id for unix error {0}", e);
throw new RuntimeException("获取进程ID失败", e);
}
} else if (process instanceof ProcessHandle) {
logger.error("java9+process instanceof ProcessHandle ");
// Java 9+ 推荐方式:ProcessHandle API
pid = ((ProcessHandle) process).pid();
} else {
throw new UnsupportedOperationException("不支持当前JDK的进程ID获取");
logger.error("jdk8 换方法执行");
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
Field declaredField = clazz.getDeclaredField("pid");
declaredField.setAccessible(true);
pid = declaredField.getInt(process);
// throw new UnsupportedOperationException("不支持当前JDK的进程ID获取");
}
} catch (Throwable e) {
} catch (NoSuchMethodError e) {
// 降级走 JDK 8 反射逻辑
try {
Class<?> clazz = Class.forName("java.lang.UNIXProcess");
Field declaredField = clazz.getDeclaredField("pid");
declaredField.setAccessible(true);
pid = declaredField.getInt(process);
} catch (Exception ex) {
// 最终容错,返回-1不中断任务
pid = -1;
logger.error("get process id for unix error {0}", e);
// throw new UnsupportedOperationException("不支持当前JDK的进程ID获取");
}
} catch (Throwable e) {
logger.error("get process id for unix error ", e);
throw new UnsupportedOperationException("不支持当前JDK的进程ID获取");
}
}
return String.valueOf(pid);
......@@ -89,7 +113,7 @@ public class ProcessUtil {
command = "kill " + pid;
}
try {
//杀掉进程
// 杀掉进程
process = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
String line;
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论