package com.zt.life.modules.mainPart.utils.OSUtils; import com.zt.common.exception.RenException; import java.io.BufferedReader; import java.io.InputStreamReader; public class ProcessUtils { public static long getProcessId(Process process) { long pid = -1; java.lang.reflect.Field field = null; try { if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) { field = process.getClass().getDeclaredField("handle"); } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) { field = process.getClass().getDeclaredField("pid"); } else { throw new RenException("暂不支持该操作系统:获取进程号"); } field.setAccessible(true); pid = Kernel32.INSTANCE.GetProcessId((Long)field.get(process)); } catch (Exception e) { e.printStackTrace(); } return pid; } public static void killProcess(long pid) { try { Process process = null; if (System.getProperty("os.name").toLowerCase().indexOf("windows") > -1) { process = Runtime.getRuntime().exec(new String[]{"cmd", "/c", "taskkill /PID "+pid+" /T /F"}); } else if (System.getProperty("os.name").toLowerCase().indexOf("linux") > -1) { process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", "kill -9 "+pid}); } else { throw new RenException("暂不支持该操作系统:终止进程!"); } int exitCode = process.waitFor(); } catch (Exception e) { e.printStackTrace(); } } public static boolean isProcessAlive(long pid) { boolean isAlive = false; try { // 根据不同的操作系统,构造不同的命令 String os = System.getProperty("os.name").toLowerCase(); String command; if (os.contains("win")) { // Windows 系统 command = "tasklist /FI \"PID eq " + pid + "\""; } else { // Unix-like 系统 command = "ps -p " + pid; } Process process = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; // 判断输出中是否包含进程信息 while ((line = reader.readLine()) != null) { if (line.contains(String.valueOf(pid))) { isAlive = true; break; } } reader.close(); } catch (Exception e) { e.printStackTrace(); } return isAlive; } }