如何获得我的Java进程的id ?
我知道有一些平台相关的黑客,但我更喜欢一个更通用的解决方案。
如何获得我的Java进程的id ?
我知道有一些平台相关的黑客,但我更喜欢一个更通用的解决方案。
当前回答
以下是我的解决方案:
public static boolean isPIDInUse(int pid) {
try {
String s = null;
int java_pid;
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("@")));
if (java_pid == pid) {
System.out.println("In Use\n");
return true;
}
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return false;
}
其他回答
我最新发现的是有一个系统属性叫做sun.java.launcher.pid,至少在linux上是可用的。我的计划是使用它,如果没有发现它使用JMX bean。
对于旧的JVM,在linux中…
private static String getPid() throws IOException {
byte[] bo = new byte[256];
InputStream is = new FileInputStream("/proc/self/stat");
is.read(bo);
for (int i = 0; i < bo.length; i++) {
if ((bo[i] < '0') || (bo[i] > '9')) {
return new String(bo, 0, i);
}
}
return "-1";
}
我发现了一个可能有点极端的解决方案,除了Windows 10之外,我没有在其他操作系统上尝试过,但我认为它值得注意。
如果您发现自己使用J2V8和nodejs,那么可以运行一个简单的javascript函数,返回java进程的pid。
这里有一个例子:
public static void main(String[] args) {
NodeJS nodeJS = NodeJS.createNodeJS();
int pid = nodeJS.getRuntime().executeIntegerScript("process.pid;\n");
System.out.println(pid);
nodeJS.release();
}
自Java 9以来,有一个方法process . getpid(),它返回进程的本机ID:
public abstract class Process {
...
public long getPid();
}
要获取当前Java进程的进程ID,可以使用ProcessHandle接口:
System.out.println(ProcessHandle.current().pid());
下面的方法尝试从java.lang.management.ManagementFactory中提取PID:
private static String getProcessId(final String fallback) {
// Note: may fail in some JVM implementations
// therefore fallback has to be provided
// something like '<pid>@<hostname>', at least in SUN / Oracle JVMs
final String jvmName = ManagementFactory.getRuntimeMXBean().getName();
final int index = jvmName.indexOf('@');
if (index < 1) {
// part before '@' empty (index = 0) / '@' not found (index = -1)
return fallback;
}
try {
return Long.toString(Long.parseLong(jvmName.substring(0, index)));
} catch (NumberFormatException e) {
// ignore
}
return fallback;
}
例如,只需调用getProcessId("<PID>")。