Skip to content
Advertisement

How do I find my PID in Java or JRuby on Linux?

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?

Advertisement

Answer

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:

String pid = new File("/proc/self").getCanonicalFile().getName();

In JRuby, you can use the same solution:

pid = java.io.File.new("/proc/self").canonical_file.name

Special thanks to the #stackoverflow channel on free node for helping me solve this! (specifically, Jerub, gregh, and Topdeck)

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement