java 9及更高版操作和查询本地进程中信息:如关闭window或Linux中的进程

java 9及更高版操作和查询本地进程中信息:如关闭window或Linux中的进程

打开某个进程并获取进程信息

java 复制代码
    /**
     * 打开某个进程并获取进程信息
     * @throws IOException
     */
    public static void startAndGetProcessInfo() throws IOException {
        //这里可以输入命令 如cmd命令、打开软件命令:这里以打开window系统的计算器为例
        //ProcessBuilder是jdk 1.5提供的
        ProcessBuilder pb = new ProcessBuilder("calc.exe");
        String na = "<not available>";
        //开启计算器进程
        Process p = pb.start();
        //p.info()是Java 9才有的
        ProcessHandle.Info info = p.info();
        System.out.printf("Process ID: %s%n", p.pid());
        System.out.printf("Command name: %s%n", info.command().orElse(na));
        System.out.printf("Command line: %s%n", info.commandLine().orElse(na));
        System.out.printf("Start time: %s%n",info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()).toLocalDateTime().toString()).orElse(na));
        System.out.printf("Arguments: %s%n",info.arguments().map(a -> Stream.of(a).collect(Collectors.joining(" "))) .orElse(na));
        System.out.printf("User: %s%n", info.user().orElse(na));

        // 一般来说,对于计算器这样的独立进程,不需要读取其输出或等待其终止
        // 但对于良好的编程习惯,特别是需要确保进程资源被正确关闭时,可以考虑添加以下代码
        // process.waitFor(); // 等待进程执行完毕
        // process.getInputStream().close();
        // process.getOutputStream().close();
        // process.getErrorStream().close();
    }

在Java 9中,ProcessHandle类提供了操作和查询本地进程中信息的能力

java 复制代码
 public static void processHandleTest() {
        // 获取当前进程的进程ID(PID)
        long currentProcessId = ProcessHandle.current().pid();
        System.out.println("Current Process ID: " + currentProcessId);

        // 获取当前进程的子进程列表
        ProcessHandle.current().children().forEach(child -> {
            System.out.println("Child Process ID: " + child.pid() + ", Name: " + child.info().command().orElse("<unknown command>"));
        });

        // 获取当前进程的父进程
        Optional<ProcessHandle> parent = ProcessHandle.current().parent();
        if(parent.isPresent()){
            ProcessHandle processHandle = parent.get();
            System.out.println("Parent Process ID: " + processHandle.pid() + ", Name: " + processHandle.info().command().orElse("<unknown command>"));
        }

        //获取资源管理器中的所有进程并按照可执行路径名称排序
        ProcessHandle.allProcesses()
                .sorted(Comparator.comparing(x->x.info().command().orElse("")))
                .forEach(processHandle -> System.out.println("processHandle Process ID: " + processHandle.pid() + ", Name: " + processHandle.info().command().orElse("<unknown command>")));
        //关闭某个软件的所有进程
       // ProcessHandle.allProcesses().filter(x->x.info().command().orElse("").equals("D:\\Program Files\\Google\\Chrome\\Application\\chrome.exe")).collect(Collectors.toList()).forEach(x->destroyProcessById(x.pid()));

        // 假设我们有一个目标进程的PID
       // long targetProcessId = 31384; // 请替换为实际的进程ID
        // 尝试获取并销毁目标进程
       // destroyProcessById(targetProcessId);
    }

销毁进程

java 复制代码
/**
     * 销毁进程
     * @param targetProcessId
     */
    private static void destroyProcessById(long targetProcessId) {
        Optional<ProcessHandle> targetProcessOpt = ProcessHandle.of(targetProcessId);
        if (targetProcessOpt.isPresent()) {
            ProcessHandle targetProcess = targetProcessOpt.get();
            targetProcess.destroy(); // 发送SIGTERM信号
            targetProcess.onExit().thenRun(() -> {
                System.out.println("目标进程Id " + targetProcess.pid() + " 已经被销毁");
            });
        } else {
            System.out.println("没有找到对应的进程Id " + targetProcessId);
        }
    }

完整代码

java 复制代码
import java.io.IOException;
import java.time.ZoneId;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class ProcessHandleDemo {

    public static void main(String[] args) throws Exception {
        processHandleTest();
    }

    /**
     * 打开某个进程并获取进程信息
     * @throws IOException
     */
    public static void startAndGetProcessInfo() throws IOException {
        //这里可以输入命令 如cmd命令、打开软件命令:这里以打开window系统的计算器为例
        //ProcessBuilder是jdk 1.5提供的
        ProcessBuilder pb = new ProcessBuilder("calc.exe");
        String na = "<not available>";
        //开启计算器进程
        Process p = pb.start();
        //p.info()是Java 9才有的
        ProcessHandle.Info info = p.info();
        System.out.printf("Process ID: %s%n", p.pid());
        System.out.printf("Command name: %s%n", info.command().orElse(na));
        System.out.printf("Command line: %s%n", info.commandLine().orElse(na));
        System.out.printf("Start time: %s%n",info.startInstant().map(i -> i.atZone(ZoneId.systemDefault()).toLocalDateTime().toString()).orElse(na));
        System.out.printf("Arguments: %s%n",info.arguments().map(a -> Stream.of(a).collect(Collectors.joining(" "))) .orElse(na));
        System.out.printf("User: %s%n", info.user().orElse(na));

        // 一般来说,对于计算器这样的独立进程,不需要读取其输出或等待其终止
        // 但对于良好的编程习惯,特别是需要确保进程资源被正确关闭时,可以考虑添加以下代码
        // process.waitFor(); // 等待进程执行完毕
        // process.getInputStream().close();
        // process.getOutputStream().close();
        // process.getErrorStream().close();
    }

    /**
     * 在Java 9中,ProcessHandle类提供了操作和查询本地进程中信息的能力
     */
    public static void processHandleTest() {
        // 获取当前进程的进程ID(PID)
        long currentProcessId = ProcessHandle.current().pid();
        System.out.println("Current Process ID: " + currentProcessId);

        // 获取当前进程的子进程列表
        ProcessHandle.current().children().forEach(child -> {
            System.out.println("Child Process ID: " + child.pid() + ", Name: " + child.info().command().orElse("<unknown command>"));
        });

        // 获取当前进程的父进程
        Optional<ProcessHandle> parent = ProcessHandle.current().parent();
        if(parent.isPresent()){
            ProcessHandle processHandle = parent.get();
            System.out.println("Parent Process ID: " + processHandle.pid() + ", Name: " + processHandle.info().command().orElse("<unknown command>"));
        }

        //获取资源管理器中的所有进程并按照可执行路径名称排序
        ProcessHandle.allProcesses()
                .sorted(Comparator.comparing(x->x.info().command().orElse("")))
                .forEach(processHandle -> System.out.println("processHandle Process ID: " + processHandle.pid() + ", Name: " + processHandle.info().command().orElse("<unknown command>")));
        //关闭某个软件的所有进程
       // ProcessHandle.allProcesses().filter(x->x.info().command().orElse("").equals("D:\\Program Files\\Google\\Chrome\\Application\\chrome.exe")).collect(Collectors.toList()).forEach(x->destroyProcessById(x.pid()));

        // 假设我们有一个目标进程的PID
        long targetProcessId = 31384; // 请替换为实际的进程ID
        // 尝试获取并销毁目标进程
        destroyProcessById(targetProcessId);
    }

    /**
     * 销毁进程
     * @param targetProcessId
     */
    private static void destroyProcessById(long targetProcessId) {
        Optional<ProcessHandle> targetProcessOpt = ProcessHandle.of(targetProcessId);
        if (targetProcessOpt.isPresent()) {
            ProcessHandle targetProcess = targetProcessOpt.get();
            targetProcess.destroy(); // 发送SIGTERM信号
            targetProcess.onExit().thenRun(() -> {
                System.out.println("目标进程Id " + targetProcess.pid() + " 已经被销毁");
            });
        } else {
            System.out.println("没有找到对应的进程Id " + targetProcessId);
        }
    }

}
相关推荐
古法老登瞎折腾2 小时前
大数据智能运维实战(十一):运维 MCP 的工程化——权限、限流、审计与错误处理
java·大数据·运维·spring ai·mcp
智能运维指南3 小时前
研制过程“两张皮“怎么破:研制一体化支撑平台的定位、能力边界与落地前提
java·前端·人工智能·嘉为蓝鲸
yz_aiks4 小时前
Spring AI 2.1 ChatMemory 已过时用什么替代:迁移到 Session Memory 实战(JDBC 存储与会话压缩)
java·spring boot·大模型·ai agent·spring ai
金銀銅鐵4 小时前
[Java] 用 GUI 展示 EnumMap 增删键值对时的内部变化
java·后端·ai编程
学长毕设4 小时前
基于SpringBoot的上门洗车服务系统设计与实现
java·spring boot·后端
jason成都4 小时前
RTKLIB-Java 多基线联合RTK:FIX率从0%到91.5%的三层根因修复
java·gnss·rtklib·rtklib_java
鱼宵5 小时前
Stream 终端操作一次讲透:collect、count、reduce 怎么选
java·stream·终端操作
白山编程大哥5 小时前
Java 后端如何优雅地把 List 集合返回给前端
java·前端·list
Linux运维技术栈5 小时前
CVE-2026-91403 高危漏洞修复:Rocky Linux 9 多版本 JDK 环境清理实操
java·linux·运维
On The Road :5 小时前
Java 多线程详解:从入门到线程安全
java·python·安全