在Java中判断一个进程ID(PID)是否存活,可以使用Java的Process类来执行操作系统命令,并获取命令的输出结果。

下面是一个示例代码,可以根据给定的PID判断进程是否存活:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ProcessUtils {

    public static boolean isProcessAlive(int pid) {
        String os = System.getProperty("os.name").toLowerCase();
        String command = "";
        if (os.contains("win")) {
            command = "tasklist";
        } else if (os.contains("nix") || os.contains("nux") || os.contains("mac")) {
            command = "ps -p " + pid;
        } else {
            throw new UnsupportedOperationException("Unsupported operating system: " + os);
        }

        try {
            Process process = Runtime.getRuntime().exec(command);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                if (os.contains("win")) {
                    if (line.contains(" " + pid + " ")) {
                        return true;
                    }
                } else {
                    if (line.contains("" + pid)) {
                        return true;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }

    public static void main(String[] args) {
        int pid = 12345; // 替换为需要判断的进程ID
        boolean isAlive = isProcessAlive(pid);
        System.out.println("Process with PID " + pid + " is alive: " + isAlive);
    }
}

上述代码中,根据不同的操作系统,使用不同的命令来获取进程列表。在Windows系统中,使用tasklist命令获取进程列表,然后判断PID是否存在于列表中;在类Unix系统中,使用ps -p命令获取进程信息,然后判断是否存在该PID的进程

java 判断pid是否存活

原文地址: https://www.cveoy.top/t/topic/icFv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录