现在的位置: 首页 > 综合 > 正文

Get the PID (pure Java solution)

2018年05月23日 ⁄ 综合 ⁄ 共 710字 ⁄ 字号 评论关闭

This solution use the RuntimeMXBean. The name of the bean contains the pid (ex. 12345@localhost).

Warning : The returned name string can be any arbitrary string and a Java virtual machine implementation can choose to embed platform-specific useful information in the returned name string.

On the Sun JVM (Windows plateform), the PID is present.

public class SystemUtils {
  
  private SystemUtils() {}
  
  public static long getPID() {
    String processName =
      java.lang.management.ManagementFactory.getRuntimeMXBean().getName();
    return Long.parseLong(processName.split("@")[0]);
  }

  public static void main(String[] args) {
    String msg = "My PID is " + SystemUtils.getPID();
    
    javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
        null, msg, "SystemUtils", javax.swing.JOptionPane.DEFAULT_OPTION);

  }

}

The result is

抱歉!评论已关闭.