How do I get the id of my Java process?
I know there are several platform-dependent hacks, but I would prefer a more generic solution.
You could use JNA. Unfortunately there is no common JNA API to get the current process ID yet, but each platform is pretty simple:
Make sure you have jna-platform.jar
then:
int pid = Kernel32.INSTANCE.GetCurrentProcessId();
Declare:
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary("c", CLibrary.class);
int getpid ();
}
Then:
int pid = CLibrary.INSTANCE.getpid();
Under Java 9 the new process API can be used to get the current process ID. First you grab a handle to the current process, then query the PID:
long pid = ProcessHandle.current().pid();