Sunday, March 04, 2007

One More Way How to Get the Current PID in Java

Yesterday I wrote a post about getting the current PID in Java.

I knew that there had to be at least one more way to do this because I read about using perl and the Runtime.exec() method to get the PID. But I didn't like the perl part of the hack so I didn't mention it in my post.

Today after some time playing with bash and an annoying behavior of Runtime.exec(String) method I came up with a 5th approach of retrieving the current PID. This approach uses $PPID and Runtime.exec(String[]):

public class Pid {
public static void main(String[] args) throws IOException {
  byte[] bo = new byte[100];
  String[] cmd = {"bash", "-c", "echo $PPID"};
  Process p = Runtime.getRuntime().exec(cmd);
  System.out.println(new String(bo));
The code is pretty straight forward. Get Runtime object, call exec(String[]) method pass it bash -c "echo $PPID" (after splitting it into a String array) and read the output.

Why not to pass the command as one string? Because of problems with quotes described in this bug report.

As I mentioned before even this approach is not perfect, because it depends on *nix and bash, but it is an improvement compared to depending on perl :)

1 comment:

abd said...

Very useful tip, thanks a lot :)