I am trying to get processes from the machine and collect related information for each process.
I am writing this functionality in Java with the help of JNA
public static List<ProcessInfo> getProcessList() throws Exception {
/* Initialize the empty process list. */
List<ProcessInfo> processList = new ArrayList<ProcessInfo>();
/* Create the process snapshot. */
WinNT.HANDLE snapshot = Kernel32.INSTANCE.CreateToolhelp32Snapshot(Tlhelp32.TH32CS_SNAPPROCESS, new WinDef.DWORD(0));
Tlhelp32.PROCESSENTRY32.ByReference pe = new Tlhelp32.PROCESSENTRY32.ByReference();
for (boolean more = Kernel32.INSTANCE.Process32First(snapshot, pe); more; more = Kernel32.INSTANCE.Process32Next(snapshot, pe)) {
/* Open this process; ignore processes that we cannot open. */
WinNT.HANDLE hProcess = Kernel32.INSTANCE.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_QUERY_LIMITED_INFORMATION, /* PROCESS_QUERY_LIMITED_INFORMATION */false, pe.th32ProcessID.intValue());
if (hProcess == null) {
continue;
}
/* Get the image name. */
char[] imageNameChars = new char[1024];
IntByReference imageNameLen = new IntByReference(imageNameChars.length);
if (!Kernel32.INSTANCE.QueryFullProcessImageName(hProcess, 0, imageNameChars, imageNameLen)) {
throw new Exception("Couldn't get process image name for "
+ pe.th32ProcessID.intValue());
}
/* Add the process info to our list. */
processList.add(new ProcessInfo(pe.th32ProcessID.intValue(), pe.th32ParentProcessID.intValue(), new String(imageNameChars, 0, imageNameLen.getValue())));
/* Close the process handle. */
Kernel32.INSTANCE.CloseHandle(hProcess);
}
/* Close the process snapshot. */
Kernel32.INSTANCE.CloseHandle(snapshot);
/* Return the process list. */
return processList;
}
Now I am getting the error (87) on OpenProcess function. This code is working from User session and I am getting the result but while running this code from window service of the local system then it is failing.