java windows 取所有任务,如何从Java获取Windows进程说明?

Here is the code to get list of currently running process in 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);

}

}

}

But I am unable to get description of the process/service in output.Kindly provide solution to get process description of each running proceess. Thanks in advance.

解决方案

Instead of loading and invoking Kernel32 you could simply use the following code snippet in windows which uses the Runtime to execute a native process:

public List 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 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.emptyList();

}

and then execute the command which invokes the Windows Management Information Command-line:

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

processName should contain the name of the running application or exe you try to get information from.

The returned list will then contain the line output of the status information of the running application. The first entry will contain header-information for the respective fields while the following entries will contain information on all matching process names.

Further infos on WMIC:

HTH

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值