On a POSIX-compliant system, is there a way to get the process ID of
the JVM running the current code?
There is no standard means of obtaining the process ID of
the JVM. The most efficient way of implementing this is to write a
JNI method that produces this information.
However, simply returning the value of the POSIX getpid() function may not be portable.
Different POSIX systems have different threading models, and it is
possible on some systems for threads to receive their own process
ids. Therefore you must make sure that the method you write really
produces the process id of the JVM and not just the process ID of the current
Rather than go to the trouble of writing a JNI method that may or may
not be portable to other POSIX systems, you can do something that is
guaranteed to work on any POSIX system. If you are deploying Java on
POSIX, you are probably starting your applications from a simple shell
script. The easiest way to convey the process ID of the JVM to a Java
process is to get the ID of the shell, $$ for Bourne-derived
shells, and pass it as an argument to the Java program. Whether it's
the first or last argument, or conveyed with a PID flag, is up to you.
When you execute the Java program, be sure to use the shell's exec
command. This will replace the shell with the new Java process, but
preserve the same process id. For example:
exec java helloworld $$