1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32 package org.spf4j.os;
33
34 import com.sun.jna.Pointer;
35 import com.sun.jna.platform.win32.Kernel32;
36 import com.sun.jna.platform.win32.WinNT;
37 import java.lang.management.ManagementFactory;
38 import java.lang.management.RuntimeMXBean;
39 import java.lang.reflect.Field;
40 import javax.annotation.Signed;
41 import org.spf4j.base.UncheckedExecutionException;
42
43
44
45
46
47 public final class ProcessUtil {
48
49 private static final int PID = parsePid();
50
51 private ProcessUtil() { }
52
53 private static int parsePid() {
54 RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
55 String mxBeanName = runtimeMxBean.getName();
56 int atIdx = mxBeanName.indexOf('@');
57 if (atIdx < 0) {
58 return -1;
59 } else {
60 return Integer.parseInt(mxBeanName.substring(0, atIdx));
61 }
62 }
63
64
65
66
67 @Signed
68 public static int getPid() {
69 return PID;
70 }
71
72
73 public static int getPid(final Process p) {
74 if (OperatingSystem.isWindows()) {
75 return getWindowsPid(p);
76 }
77 return getUnixPid(p);
78 }
79
80 private static int getUnixPid(final Process p) {
81 try {
82 Field pidF = p.getClass().getDeclaredField("pid");
83 pidF.setAccessible(true);
84 return pidF.getInt(p);
85 } catch (IllegalAccessException | NoSuchFieldException | SecurityException ex) {
86 throw new UncheckedExecutionException("Cannot get PID for " + p, ex);
87 }
88 }
89
90 private static int getWindowsPid(final Process p) {
91 Field f;
92 long lHandle;
93 try {
94 f = p.getClass().getDeclaredField("handle");
95 f.setAccessible(true);
96 lHandle = f.getLong(p);
97 } catch (NoSuchFieldException | SecurityException | IllegalAccessException ex) {
98 throw new UncheckedExecutionException("Cannot get PID for " + p, ex);
99 }
100
101 Kernel32 kernel = Kernel32.INSTANCE;
102 WinNT.HANDLE handle = new WinNT.HANDLE();
103 handle.setPointer(Pointer.createConstant(lHandle));
104 return kernel.GetProcessId(handle);
105 }
106
107 }