how to write java program get pid?
-
This is far too vague. Get the pid of what?unwind– unwind2009-04-15 07:37:46 +00:00Commented Apr 15, 2009 at 7:37
-
Make your question more specific. Otherwise - close++;Yuval Adam– Yuval Adam2009-04-15 07:43:00 +00:00Commented Apr 15, 2009 at 7:43
-
duplicates of stackoverflow.com/questions/138097/… and stackoverflow.com/questions/35842/process-id-in-java ?chburd– chburd2009-04-15 08:20:33 +00:00Commented Apr 15, 2009 at 8:20
Add a comment
|
3 Answers
How a Java Application Can Discover its Process ID (PID)
Not very straightforward, but apparently there is no "official" way.
Comments
You can do this using JMX, but beware. The below is not an officially supported mechanism and could change. However, I've used this in the past and it works fine.
RuntimeMXBean rmxb = ManagementFactory.getRuntimeMXBean();
System.err.println("pid: " + rmxb.getName());
will print {pid}@hostname
Comments
I don't believe this is something Java supplies. For a start, it breaks the platform-independent nature. I can see two ways to approach it, both assuming you're running under a UNIX-type system.
- provide a JNI which will call
getpid()and return it. - use system or one of the Runtime methods to run an external program which will call
getppid()to get the PID of its parent (i.e., Java), or worse case, walk up the process tree until you find Java itself.