1 package net.bull.javamelody.internal.model;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.lang.management.ManagementFactory;
7 import java.lang.management.RuntimeMXBean;
8 import java.nio.charset.Charset;
9 import java.util.Locale;
10 import java.util.StringTokenizer;
11
12 import net.bull.javamelody.internal.common.InputOutput;
13
14
17 public final class PID {
18 private PID() {
19 super();
20 }
21
22
25 public static String getPID() {
26 String pid = System.getProperty("pid");
27 if (pid == null) {
28
29 final RuntimeMXBean rtb = ManagementFactory.getRuntimeMXBean();
30 final String processName = rtb.getName();
31
32
33
34
35
36
37 if (processName.indexOf('@') != -1) {
38 pid = processName.substring(0, processName.indexOf('@'));
39 } else {
40 pid = getPIDFromOS();
41 }
42 System.setProperty("pid", pid);
43 }
44 return pid;
45 }
46
47 static String getPIDFromOS() {
48 String pid;
49
50
51
52
53 final String[] cmd;
54 File tempFile = null;
55 Process process = null;
56 try {
57 try {
58 if (!System.getProperty("os.name").toLowerCase(Locale.ENGLISH)
59 .contains("windows")) {
60 cmd = new String[] { "/bin/sh", "-c", "echo $$ $PPID" };
61 } else {
62
63 tempFile = File.createTempFile("getpids", ".exe");
64
65
66 extractGetPid(tempFile);
67 cmd = new String[] { tempFile.getAbsolutePath() };
68 }
69 process = Runtime.getRuntime().exec(cmd);
70 final String processOutput = InputOutput.pumpToString(process.getInputStream(),
71 Charset.defaultCharset());
72 final StringTokenizer stok = new StringTokenizer(processOutput);
73 stok.nextToken();
74 pid = stok.nextToken();
75
76
77
78 process.waitFor();
79 } finally {
80 if (process != null) {
81
82 process.getInputStream().close();
83 process.getOutputStream().close();
84 process.getErrorStream().close();
85 process.destroy();
86 }
87 if (tempFile != null && !tempFile.delete()) {
88 tempFile.deleteOnExit();
89 }
90 }
91 } catch (final InterruptedException | IOException e) {
92 pid = e.toString();
93 }
94 return pid;
95 }
96
97 private static void extractGetPid(File tempFile) throws IOException {
98 try (InputStream input = PID.class
99 .getResourceAsStream("/net/bull/javamelody/resource/getpids.exe")) {
100 InputOutput.pumpToFile(input, tempFile);
101 }
102 }
103 }
104