본문 바로가기

컴퓨터/IT

Howto find out Process ID from java in linux

The following stuff works on Linux with JDK1.2 for getting the process id (and that of the parent).

Steps to do:
javac unistd.java
javah -jni -o j_unistd.h unistd
JHOME=/usr/lib/jdk1.2.2
gcc -shared -I. -I"$JHOME"/include -I"$JHOME"/include/linux 
        j_unistd.c -o libj_unistd.so
export LD_LIBRARY_PATH=.
java unistd


And the sources (the header is generated by javah)

unistd.java
import java.util.Properties;
public class unistd {
        public static native long getpid();
        public static native long getppid();
        static {
                System.loadLibrary("j_unistd");
        }
        public static void main(String argv[]) {
                System.out.println(getpid() + " " + getppid());
        }
}


j_unistd.c
#include "j_unistd.h"
#include <unistd.h>
#include <string.h>
JNIEXPORT jlong JNICALL Java_unistd_getpid
  (JNIEnv *envp, jclass clazz)
  {
        return getpid();
  }
JNIEXPORT jlong JNICALL Java_unistd_getppid
  (JNIEnv *envp, jclass clazz)
  {
        return getppid();
  }