gpt4 book ai didi

java - 如何从Java获取Windows进程描述?

转载 作者:行者123 更新时间:2023-12-01 18:38:01 24 4
gpt4 key购买 nike

这是获取 Windows 中当前正在运行的进程列表的代码。

  import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.Tlhelp32;
import com.sun.jna.platform.win32.WinDef;
import com.sun.jna.platform.win32.WinNT;
import com.sun.jna.win32.W32APIOptions;
import com.sun.jna.Native;

public class ListProcesses {
public static void main(String[] args) {
Kernel32 kernel32 = (Kernel32) Native.loadLibrary(Kernel32.class, W32APIOptions.UNICODE_OPTIONS);

Tlhelp32.PROCESSENTRY32.ByReference processEntry = new Tlhelp32.PROCESSENTRY32.ByReference();
WinNT.HANDLE snapshot = kernel32.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
try {
while (kernel32.Process32Next(snapshot, processEntry)) {
System.out.println(processEntry.th32ProcessID + "\t" + Native.toString(processEntry.szExeFile)+"\t"+processEntry.readField(""));
}

}

finally {
kernel32.CloseHandle(snapshot);
}
}
}

但是我无法在输出中获取进程/服务的描述。请提供解决方案来获取每个正在运行的进程的进程描述。提前致谢。

最佳答案

您可以简单地在 Windows 中使用以下代码片段,它使用运行时来执行 native 进程,而不是加载和调用 Kernel32:

public List<String> execCommand(String ... command)
{
try
{
// execute the desired command
Process proc = null;
if (command.length > 1)
proc = Runtime.getRuntime().exec(command);
else
proc = Runtime.getRuntime().exec(command[0]);

// process the response
String line = "";
List<String> output = new ArrayList<>();
try (BufferedReader input = new BufferedReader(new InputStreamReader(proc.getInputStream())))
{
while ((line = input.readLine()) != null)
{
output.add(line);
}
}
return output;
}
catch (IOException e)
{
e.printStackTrace();
}
return Collections.<String>emptyList();
}

然后执行调用 Windows Management Information Command-line 的命令:

List<String> output = execCommand("wmic.exe PROCESS where name='"+processName+"'");

processName 应包含正在运行的应用程序或您尝试从中获取信息的 exe 的名称。

返回的列表将包含正在运行的应用程序的状态信息的行输出。第一个条目将包含各个字段的 header 信息,而以下条目将包含所有匹配进程名称的信息。

有关 WMIC 的更多信息:

HTH

关于java - 如何从Java获取Windows进程描述?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20996015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com