Java 判断进程是否存活:完整代码示例和跨平台解决方案
在Java中判断一个进程ID(PID)是否存活,可以使用Java的Process类来执行操作系统命令,并获取命令的输出结果。\n\n下面是一个示例代码,可以根据给定的PID判断进程是否存活:\n\njava\nimport java.io.BufferedReader;\nimport java.io.IOException;\nimport java.io.InputStreamReader;\n\npublic class ProcessUtils {\n\n public static boolean isProcessAlive(int pid) {\n String os = System.getProperty("os.name").toLowerCase();\n String command = "";\n if (os.contains("win")) {\n command = "tasklist";\n } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {\n command = "ps -p " + pid;\n } else {\n throw new UnsupportedOperationException("Unsupported operating system: " + os);\n }\n\n try {\n Process process = Runtime.getRuntime().exec(command);\n BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));\n String line;\n while ((line = reader.readLine()) != null) {\n if (os.contains("win")) {\n if (line.contains(" " + pid + " ")) {\n return true;\n }\n } else {\n if (line.contains("" + pid)) {\n return true;\n }\n }\n }\n } catch (IOException e) {\n e.printStackTrace();\n }\n\n return false;\n }\n\n public static void main(String[] args) {\n int pid = 12345; // 替换为需要判断的进程ID\n boolean isAlive = isProcessAlive(pid);\n System.out.println("Process with PID " + pid + " is alive: " + isAlive);\n }\n}\n\n\n上述代码中,根据不同的操作系统,使用不同的命令来获取进程列表。在Windows系统中,使用tasklist命令获取进程列表,然后判断PID是否存在于列表中;在类Unix系统中,使用ps -p命令获取进程信息,然后判断是否存在该PID的进程。
原文地址: https://www.cveoy.top/t/topic/pVlq 著作权归作者所有。请勿转载和采集!