Get the PID (pure Java solution)Tag(s): Environment


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

For a Java-JNI solution, see this HowTo.


blog comments powered by Disqus