Retrieving UNIX ProcessID in Java

Usually when we create a daemon in Unix/Linux, we need know the process id of the process in order to restart the process or kill it. And there’s no Java API for returning the JVM process ID. So this is a solution for getting the JVM process ID. Note that the example is only work for Unix-based OS only. I’ve implemented it on a BSD box.

First we need an application to output a UNIX systemcall getppid(). So i create getppid.c

getppid.c
main() {
  printf("%d", getppid());
}

After compiling it, lets create the Java code,

Pid.java

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Pid {
  public static long getProcessID() {
    long pid = -1;
    try {
      Process p = Runtime.getRuntime().exec("./getppid");
      BufferedReader br = new BufferedReader(
        new InputStreamReader(p.getInputStream()));
      String t = null;
      while (null != (t = br.readLine())) {
        pid = Long.parseLong(t);
      }
    } catch(Exception e) {
      e.printStackTrace();
    }
    return pid;
  }

  public static void main(String[] args) {
    System.out.println(getProcessID());
  }
}

Compile and run. Now whenever you call Pid.getProcessID() you’ll get the JVM process ID. Btw, you can replace the getppid.c with some shell script. For example:

getppid.sh

/bin/sh
echo $PID

Just make sure that the script has the execute permission: chmod +x getppid.sh.

3 komentar

  1. Ady Wicaksono bilang:

    Jajalen ping pindo hasil pid-ne podo gak? nek bedo berarti dudu pid-e JVM, ning program ./getpid sing di fork()

    April 9th, 2007 at 22:52
  2. Marcus Vale bilang:

    The shell script approach worked for me, after I rewrote it as:
    #!/bin/posix/sh
    echo $PPID

    May 10th, 2007 at 01:43
  3. Peter Lawrey bilang:

    A VM dependant way to do this (works on the Sun JVM) is to call

    ManagementFactory.getRuntimeMXBean().getName()

    which print the process id and the hostname. Like

    4812@myhostname

    May 12th, 2008 at 20:22

Tinggalkan Komentar





*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word