Using the jna library to get the windows process id as adviced in other questions here on stackoverflow.
String command = "cmd /c start cmd.exe";
Process process = Runtime.getRuntime().exec(command);
long pid = windowsProcessId(process);
private static Long windowsProcessId(Process process) {
if (process.getClass().getName().equals("java.lang.Win32Process")
|| process.getClass().getName().equals("java.lang.ProcessImpl")) {
/* determine the pid on windows plattforms */
try {
Field f = process.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handl = f.getLong(process);
Kernel32 kernel = Kernel32.INSTANCE;
WinNT.HANDLE handle = new WinNT.HANDLE();
handle.setPointer(Pointer.createConstant(handl));
int ret = kernel.GetProcessId(handle);
return Long.valueOf(ret);
} catch (Throwable e) {
e.printStackTrace();
}
}
return null;
}
This however never returns the correct process id of the just started process, rather something random but usually close to the actual id. How do I get the correct process id?
Aucun commentaire:
Enregistrer un commentaire