tags:

views:

6506

answers:

5
+12  Q: 

Process ID in Java

How do I get the id of my Java process? I know there are several platform-dependent hacks, but I'm after a generic solution.

+12  A: 

There exists no platform-independent way that can be guaranteed to work in all jvm implementations. ManagementFactory.getRuntimeMXBean().getName() looks like the best (closest) solution. It's short, and probably works in every implementation in wide use.

Wouter Coekaerts
+1  A: 

It depends on where you are looking for the information from.

If you are looking for the information from the console you can use the jps command. The command gives output similar to the Unix ps command and comes with the JDK since I believe 1.5

If you are looking from the process the RuntimeMXBean (as said by Wouter Coekaerts) is probably your best choice. The output from getName() on Windows using Sun JDK 1.6 u7 is in the form [PROCESS_ID]@[MACHINE_NAME]. You could however try to execute jps and parse the result from that:

String jps = [JDK HOME] + "\\bin\\jps.exe";
Process p = Runtime.getRuntime().exec(jps);

If run with no options the output should be the process id followed by the name.

Ryan P
+1  A: 

You can check out my project: JavaSysMon on GitHub. It provides process id and a bunch of other stuff (CPU usage, memory usage) cross-platform (presently Windows, Mac OSX, Linux and Solaris)

Jez Humble
A: 

ManagementFactory.getRuntimeMXBean().getName()

sam
+1  A: 

Try Sigar - http://support.hyperic.com/display/SIGAR/Home. GPL, but very extensive APIs.

Ashwin Jayaprakash