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
:
import java.util.*;
class POSIX
{
static { System.loadLibrary ("POSIX"); }
native static int getpid ();
}
Compile it with
$ javac POSIX.java
After that you generate a header file POSIX.h
with
$ javah -jni POSIX
The 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
:
#include "POSIX.h"
#include <sys/types.h>
#include <unistd.h>
JNIEXPORT jint JNICALL Java_POSIX_getpid (JNIEnv *env, jclass cls)
{
return getpid ();
}
Now you can compile it using gcc:
$ gcc -Wall -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include -I/usr/lib/jvm/java-1.6.0-sun-1.6.0.21/include/linux -o libPOSIX.so -shared -Wl,-soname,libPOSIX.so POSIX.c -static -lc
You have to specify the location where your Java is installed. That's all. Now you can use it. Create a simple getpid program:
public class getpid
{
public static void main (String argv[])
{
System.out.println (POSIX.getpid ());
}
}
Compile it with javac getpid.java
and run it:
$ java getpid &
[1] 21983
$ 21983
The first pid is written by the shell and the second is written by the Java program after shell prompt has returned. ∎