Skip to content

Commit b3c53bf

Browse files
cgoldberglukeis
authored andcommitted
java - get process id in a way that works cross-platform
1 parent 1c52dc8 commit b3c53bf

File tree

1 file changed

+22
-9
lines changed

1 file changed

+22
-9
lines changed

java/client/src/org/openqa/selenium/os/ProcessUtils.java

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -184,15 +184,28 @@ private static void closeAllStreamsAndDestroyProcess(Process process) {
184184
}
185185

186186
static int getProcessId(Process p) {
187-
if (Platform.getCurrent().is(WINDOWS)) {
188-
throw new IllegalStateException("UnixUtils may not be used on Windows");
189-
}
190-
try {
191-
Field f = p.getClass().getDeclaredField("pid");
192-
f.setAccessible(true);
193-
return (Integer) f.get(p);
194-
} catch (Exception e) {
195-
throw new RuntimeException("Couldn't detect pid", e);
187+
if (thisIsWindows()) {
188+
try {
189+
Field f = p.getClass().getDeclaredField("handle");
190+
f.setAccessible(true);
191+
long hndl = f.getLong(p);
192+
193+
Kernel32 kernel = Kernel32.INSTANCE;
194+
WinNT.HANDLE handle = new WinNT.HANDLE();
195+
handle.setPointer(Pointer.createConstant(hndl));
196+
int pid = kernel.GetProcessId(handle);
197+
return pid;
198+
} catch (Exception e) {
199+
throw new RuntimeException("Couldn't detect pid", e);
200+
}
201+
} else {
202+
try {
203+
Field f = p.getClass().getDeclaredField("pid");
204+
f.setAccessible(true);
205+
return (Integer) f.get(p);
206+
} catch (Exception e) {
207+
throw new RuntimeException("Couldn't detect pid", e);
208+
}
196209
}
197210
}
198211

0 commit comments

Comments
 (0)