Java获取进程PID 获取父进程PID
- 2019-10-09 23:28:00
- admin
- 原创 3685
一、Java获取进程PID
1、以下两种方法都可以跨平台调用;
2、management比jnr-posix调用效率更高;
方法1:
import java.lang.management.*;
public static String getPID() {
String name = ManagementFactory.getRuntimeMXBean().getName();
return name.split("@")[0];
}
方法2:
import jnr.posix.*;
public static int getPID() {
POSIX posix = POSIXFactory.getPOSIX();
return posix.getpid();
}
二、Java获取父进程PID
import org.apache.commons.io.*;
public static String getPPID(String pid) {
try {
String stat = FileUtils.readFileToString(new File(String.format("/proc/%s/stat", pid)));
int start = stat.indexOf(" " + pid);
int end = Math.min(start+32, stat.length());
stat = stat.substring(start, end);
String[] elems = stat.split(" ");
return elems[2];
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static String getPPID() {
String pid = getPID();
return getPPID(pid);
}