1 需求
2 接口
Class Process
public abstract class Process extends Object
java.lang.Object
java.lang.Process
- Constructor Detail
- public Process()
- Method Detail
- public abstract OutputStream getOutputStream()
- public abstract InputStream getInputStream()
- public abstract InputStream getErrorStream()
- public abstract int waitFor() throws InterruptedException
- public boolean waitFor(long timeout, TimeUnit unit) throws InterruptedException
- public abstract int exitValue()
- public abstract void destroy()
- public Process destroyForcibly()
- public boolean isAlive()
3.1 示例代码:获取当前运行进程ID
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
public class Test {
public static void main(String[] args) throws InterruptedException, IOException {
String name = ManagementFactory.getRuntimeMXBean().getName();
System.out.println(name);
String pid = name.split("@")[0];
System.out.println(pid);
Process process = Runtime.getRuntime().exec("cmd /c tasklist | findstr " + pid);
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
System.out.println(br.readLine());
Thread.sleep(10000000);
}
}
3.2 示例代码:获取exec的子进程ID
import java.io.IOException;
import java.lang.reflect.Field;
public class Test {
public static void main(String[] args) throws IOException, NoSuchFieldException, IllegalAccessException {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd /c dir");
Field field = process.getClass().getDeclaredField("pid");
field.setAccessible(true);
System.out.println(field.get(process));
}
}
4 参考资料
Java程序中获取当前进程的进程ID
java获取当前进程id_Java获取当前进程ID以及所有Java进程的进程ID
java 子进程id,在Java中获取子进程ID



