package com.mes.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.management.ManagementFactory; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class ProcessUtil { private static final Logger log = LoggerFactory.getLogger(ProcessUtil.class); public static void terminateOtherJavawProcesses() { try { List pids = getAllJavawPids(); String currentPid = getCurrentPid(); String currentJarName = getJarNameByPid(currentPid); for (String pid : pids) { if (currentJarName != null && !pid.equals(currentPid) && currentJarName.equals(getJarNameByPid(pid))) { killProcess(pid); } } } catch (IOException e) { log.error(e.getMessage(), e); } } // 获取当前JVM进程PID public static String getCurrentPid() { String vmName = ManagementFactory.getRuntimeMXBean().getName(); return vmName.split("@")[0]; // 格式: "PID@hostname" } private static void killProcess(String pid) { try { Runtime.getRuntime().exec("taskkill /F /PID " + pid); log.info("已终止进程: {}", pid); } catch (Exception e) { log.error("终止进程失败: {}", pid, e); } } private static List getAllJavawPids() throws IOException { List pids = new ArrayList<>(); Process process = new ProcessBuilder("wmic", "process", "where", "name='javaw.exe'", "get", "processid").start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.matches("\\d+")) { // 匹配纯数字PID pids.add(line); } } } return pids; } private static String getJarNameByPid(String pid) throws IOException { String command = "processid=" + pid; Process process = new ProcessBuilder("wmic", "process", "where", command, "get", "commandline").start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { line = line.trim(); if(line.endsWith(".jar\"")) { String[] split = line.split("\""); if(split.length < 1) return null; String path = split[split.length - 1]; if(!path.endsWith(".jar")) return null; Path fileName = Paths.get(path).getFileName(); return fileName.toString(); } } } return null; } }