ProcessUtil.java 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package com.mes.util;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import java.io.BufferedReader;
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.lang.management.ManagementFactory;
  8. import java.nio.file.Path;
  9. import java.nio.file.Paths;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. public class ProcessUtil {
  13. private static final Logger log = LoggerFactory.getLogger(ProcessUtil.class);
  14. public static void terminateOtherJavawProcesses() {
  15. try {
  16. List<String> pids = getAllJavawPids();
  17. String currentPid = getCurrentPid();
  18. String currentJarName = getJarNameByPid(currentPid);
  19. for (String pid : pids) {
  20. if (currentJarName != null && !pid.equals(currentPid) && currentJarName.equals(getJarNameByPid(pid))) {
  21. killProcess(pid);
  22. }
  23. }
  24. } catch (IOException e) {
  25. log.error(e.getMessage(), e);
  26. }
  27. }
  28. // 获取当前JVM进程PID
  29. public static String getCurrentPid() {
  30. String vmName = ManagementFactory.getRuntimeMXBean().getName();
  31. return vmName.split("@")[0]; // 格式: "PID@hostname"
  32. }
  33. private static void killProcess(String pid) {
  34. try {
  35. Runtime.getRuntime().exec("taskkill /F /PID " + pid);
  36. log.info("已终止进程: {}", pid);
  37. } catch (Exception e) {
  38. log.error("终止进程失败: {}", pid, e);
  39. }
  40. }
  41. private static List<String> getAllJavawPids() throws IOException {
  42. List<String> pids = new ArrayList<>();
  43. Process process = new ProcessBuilder("wmic", "process", "where", "name='javaw.exe'", "get", "processid").start();
  44. try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
  45. String line;
  46. while ((line = reader.readLine()) != null) {
  47. line = line.trim();
  48. if (line.matches("\\d+")) { // 匹配纯数字PID
  49. pids.add(line);
  50. }
  51. }
  52. }
  53. return pids;
  54. }
  55. private static String getJarNameByPid(String pid) throws IOException {
  56. String command = "processid=" + pid;
  57. Process process = new ProcessBuilder("wmic", "process", "where", command, "get", "commandline").start();
  58. try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
  59. String line;
  60. while ((line = reader.readLine()) != null) {
  61. line = line.trim();
  62. if(line.endsWith(".jar\"")) {
  63. String[] split = line.split("\"");
  64. if(split.length < 1) return null;
  65. String path = split[split.length - 1];
  66. if(!path.endsWith(".jar")) return null;
  67. Path fileName = Paths.get(path).getFileName();
  68. return fileName.toString();
  69. }
  70. }
  71. }
  72. return null;
  73. }
  74. }