Java9中操作和查詢本地進程信息的示例詳解
更新時間:2024年03月10日 11:34:04 作者:ljh_learn_from_base
這篇文章主要為大家詳細介紹了Java9中操作和查詢本地進程信息的相關(guān)知識,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
打開某個進程并獲取進程信息
/**
* 打開某個進程并獲取進程信息
* @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));
// 一般來說,對于計算器這樣的獨立進程,不需要讀取其輸出或等待其終止
// 但對于良好的編程習(xí)慣,特別是需要確保進程資源被正確關(guān)閉時,可以考慮添加以下代碼
// 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>")));
//關(guān)閉某個軟件的所有進程
// 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()));
// 假設(shè)我們有一個目標進程的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() + " 已經(jīng)被銷毀");
});
} else {
System.out.println("沒有找到對應(yīng)的進程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));
// 一般來說,對于計算器這樣的獨立進程,不需要讀取其輸出或等待其終止
// 但對于良好的編程習(xí)慣,特別是需要確保進程資源被正確關(guān)閉時,可以考慮添加以下代碼
// 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>")));
//關(guān)閉某個軟件的所有進程
// 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()));
// 假設(shè)我們有一個目標進程的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() + " 已經(jīng)被銷毀");
});
} else {
System.out.println("沒有找到對應(yīng)的進程Id " + targetProcessId);
}
}
}
到此這篇關(guān)于Java9中操作和查詢本地進程信息的示例詳解的文章就介紹到這了,更多相關(guān)Java操作查詢進程信息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
eclipse創(chuàng)建springboot項目的三種方式總結(jié)
這篇文章主要介紹了eclipse創(chuàng)建springboot項目的三種方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
java Springboot實現(xiàn)多文件上傳功能
這篇文章主要為大家詳細介紹了java Springboot實現(xiàn)多文件上傳功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08
SpringBoot項目中使用@Scheduled讀取動態(tài)參數(shù)
這篇文章主要介紹了SpringBoot項目中使用@Scheduled讀取動態(tài)參數(shù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
IntelliJ?IDEA?2023.1.4?無法刷新Maven項目模塊的問題及解決方法
這篇文章主要介紹了如何排查?IDEA?自身報錯問題,本文以IntelliJ?IDEA?2023.1.4無法刷新項目Maven模塊的問題為例,給大家詳細講解,需要的朋友可以參考下2023-08-08

