I need to find the PID of the current running process on a Linux platform (it can be a system dependent solution). Java does not support getting the process ID, and JRuby currently has a bug with the Ruby method, Process.pid.
Is there another way to obtain the PID?
Java 9
finally offers an official way to do so with ProcessHandle:This:
First gets a
ProcessHandle
reference for the current process.In order to access its
pid
.No import necessary as
ProcessHandle
is part ofjava.lang
.You can use the JNI interface to call the POSIX function getpid(). It is quite straight forward. You start with a class for the POSIX functions you need. I call it
POSIX.java
:Compile it with
After that you generate a header file
POSIX.h
withThe header file contains the C prototype for the function with wraps the getpid function. Now you have to implement the function, which is quite easy. I did it in
POSIX.c
:Now you can compile it using gcc:
You have to specify the location where your Java is installed. That's all. Now you can use it. Create a simple getpid program:
Compile it with
javac getpid.java
and run it:The first pid is written by the shell and the second is written by the Java program after shell prompt has returned. ∎
If you have procfs installed, you can find the process id via the /proc/self symlink, which points to a directory whose name is the pid (there are also files here with other pertinent information, including the PID, but the directory is all you need in this case).
Thus, with Java, you can do:
In JRuby, you can use the same solution:
Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, Jerub, gregh, and Topdeck)
Spawn a shell process that will read its parent's pid. That must be our pid. Here is the running code, without exception and error handling.
This solution seems to be the best if the PID is to be obtained only to issue another shell command. It's enough to wrap the command in back quotes to pass it as an argument to another command, for example:
This may substitue the last string in the array given to
exec
call.Only tested in Linux using Sun JVM. Might not work with other JMX implementations.
You can try getpid() in JNR-Posix.
It also has a Windows POSIX wrapper that calls getpid() off of libc. No JNI needed.