使用JNA获取正在运行的进程

使用JNA获取正在运行的进程

本文介绍了使用JNA获取正在运行的进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取Windows机器上所有当前正在运行的进程的列表.

I am trying to obtain a list of all currently running processes on a windows machine.

我正在尝试通过JNA的winapi调用来尝试 EnumProcesses-> OpenProcess-> GetModuleBaseNameW-> CloseHandle它在OpenProcess调用中失败. GetLastError返回5(ERROR_ACCESS_DENIED).

I am trying it with winapi calls via JNA to EnumProcesses -> OpenProcess -> GetModuleBaseNameW -> CloseHandleIt fails at the OpenProcess call. GetLastError returns 5 (ERROR_ACCESS_DENIED).

这是我的代码:

public static final int PROCESS_QUERY_INFORMATION = 0x0400;
public static final int PROCESS_VM_READ = 0x0010;
public static final int PROCESS_VM_WRITE = 0x0020;
public static final int PROCESS_VM_OPERATION = 0x0008;


public interface Psapi extends StdCallLibrary {
    Psapi INSTANCE = (Psapi) Native.loadLibrary("Psapi", Psapi.class);

    boolean EnumProcesses(int[] ProcessIDsOut, int size, int[] BytesReturned);

    DWORD GetModuleBaseNameW(Pointer hProcess, Pointer hModule, byte[] lpBaseName, int nSize);

}

public interface Kernel32 extends StdCallLibrary {
    Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("Kernel32", Kernel32.class);

    Pointer OpenProcess(int dwDesiredAccess, boolean bInheritHandle, int dwProcessId);

    boolean CloseHandle(Pointer hObject);

}

public static void main(String[] args) {
    int[] processlist = new int[1024];
    int[] dummylist = new int[1024];
    Psapi.INSTANCE.EnumProcesses(processlist, 1024, dummylist);

    for (int pid : processlist) {
        System.out.println(pid);
        Pointer ph = Kernel32.INSTANCE.OpenProcess(PROCESS_VM_READ, false, pid);

        try {
            Thread.sleep(1000);
        } catch (Exception ignore) {
        }

        System.err.println(com.sun.jna.platform.win32.Kernel32.INSTANCE.GetLastError()); // <- 5
        System.err.println(ph); // <- null
        if (ph != null) {
            byte[] filename = new byte[512];
            Psapi.INSTANCE.GetModuleBaseNameW(ph, new Pointer(0), filename, 512);

            try {
                Thread.sleep(1000);
            } catch (Exception ignore) {
            }

            System.err.println(Native.toString(filename));
            Kernel32.INSTANCE.CloseHandle(ph);
        }

    }

}

推荐答案

PROCESS_VM_READ调用OpenProcess意味着您要读取该进程的内存.为此,您需要SE_DEBUG_PRIVLEGE.您的应用程序没有该特权,这就是为什么访问被拒绝的原因.

Calling OpenProcess with PROCESS_VM_READ means that you want to read the memory of that process. To do this, you need the SE_DEBUG_PRIVLEGE. Your application doesn't have that privilege which is why you are getting access denied.

在MSDN文章中查找 ReadProcessMemory .有关如何获得该特权的一些社区内容.

Check the MSDN article for ReadProcessMemory. There is some community content on how to acquire that privilege.

这篇关于使用JNA获取正在运行的进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 02:47