Java9中操作和查詢本地進程信息的示例詳解
更新時間:2024年03月10日 11:34:04 作者:ljh_learn_from_base
這篇文章主要為大家詳細介紹了Java9中操作和查詢本地進程信息的相關知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
打開某個進程并獲取進程信息
/**
* 打開某個進程并獲取進程信息
* @throws IOException
*/
public static void startAndGetProcessInfo() throws IOException {
//這里可以輸入命令 如cmd命令、打開軟件命令:這里以打開window系統(tǒng)的計算器為例
//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(); // 等待進程執(zhí)行完畢
// 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>"));
}
//獲取資源管理器中的所有進程并按照可執(zhí)行路徑名稱排序
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; // 請?zhí)鎿Q為實際的進程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(); // 發(fā)送SIGTERM信號
targetProcess.onExit().thenRun(() -> {
System.out.println("目標進程Id " + targetProcess.pid() + " 已經被銷毀");
});
} else {
System.out.println("沒有找到對應的進程Id " + targetProcessId);
}
}
完整代碼
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系統(tǒng)的計算器為例
//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(); // 等待進程執(zhí)行完畢
// 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>"));
}
//獲取資源管理器中的所有進程并按照可執(zhí)行路徑名稱排序
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; // 請?zhí)鎿Q為實際的進程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(); // 發(fā)送SIGTERM信號
targetProcess.onExit().thenRun(() -> {
System.out.println("目標進程Id " + targetProcess.pid() + " 已經被銷毀");
});
} else {
System.out.println("沒有找到對應的進程Id " + targetProcessId);
}
}
}
到此這篇關于Java9中操作和查詢本地進程信息的示例詳解的文章就介紹到這了,更多相關Java操作查詢進程信息內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Idea+maven搭建SSH(struts2+hibernate5+spring5)環(huán)境的方法步驟
這篇文章主要介紹了Idea+maven搭建SSH(struts2+hibernate5+spring5)環(huán)境的方法步驟,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-06-06
SpringBoot開發(fā)中十大常見陷阱深度解析與避坑指南
在Spring?Boot的開發(fā)過程中,即使是經驗豐富的開發(fā)者也難免會遇到各種棘手的問題,本文將針對Spring?Boot開發(fā)中十大常見的“坑”進行深度解析,結合具體的代碼示例,提供詳細的解決方案,幫助開發(fā)者們有效避坑2025-06-06
SpringBoot的父級依賴:spring-boot-starter-parent詳解
SpringBoot通過父級依賴spring-boot-starter-parent實現項目快速構建,它依賴于spring-boot-dependencies來統(tǒng)一管理項目中的依賴版本,省去了手動指定版本信息的麻煩,這種機制不僅規(guī)定了默認的Java版本和編碼格式2024-09-09
springboot 整合druid數據庫密碼加密功能的實現代碼
這篇文章主要介紹了springboot 整合druid數據庫密碼加密功能的實現代碼,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-01-01

