tags:

views:

2945

answers:

3

how to write java program get pid?

+5  A: 

How a Java Application Can Discover its Process ID (PID)

Not very straightforward, but apparently there is no "official" way.

Thilo
A: 

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.
paxdiablo
+1  A: 

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

Brian Agnew