如何获得我的Java进程的id ?
我知道有一些平台相关的黑客,但我更喜欢一个更通用的解决方案。
如何获得我的Java进程的id ?
我知道有一些平台相关的黑客,但我更喜欢一个更通用的解决方案。
当前回答
public static long getPID() {
String processName = java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
if (processName != null && processName.length() > 0) {
try {
return Long.parseLong(processName.split("@")[0]);
}
catch (Exception e) {
return 0;
}
}
return 0;
}
其他回答
下面的方法尝试从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>")。
基于Ashwin Jayaprakash的答案(+1) 关于Apache 2.0许可的SIGAR,下面是我如何使用它来获得当前进程的PID:
import org.hyperic.sigar.Sigar;
Sigar sigar = new Sigar();
long pid = sigar.getPid();
sigar.close();
尽管它不能在所有平台上工作,但它可以在Linux、Windows、OS X和这里列出的各种Unix平台上工作。
我发现了一个可能有点极端的解决方案,除了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.lang.management.ManagementFactory.getRuntimeMXBean().getName().split("@")[0]
对于旧的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";
}