Getting the process ID on Windows from Java

You will have to use JNI for this. Using the following code, I’ll create a DLL that provides the method getPid which will return the current process ID.

Pid.java:

public class Pid {
   public native int getPid();
   
   public int getProcessID() {
      try {
         return getPid();
      }
      catch(UnsatisfiedLinkError e) {
         e.printStackTrace();
      }
      
      return -1;
   }
   
   public static void main(String args[])
   {
      try {
         System.loadLibrary("Pid");
      }
      catch(java.lang.UnsatisfiedLinkError e) {
         e.printStackTrace();
      }

      Pid pid = new Pid();
      System.out.println(pid.getProcessID());
   }
}

Compile and run javah on it to create the pid.h header file:

javah Pid

It generates the C header file Pid.h:

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Pid */

#ifndef _Included_Pid
#define _Included_Pid
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     Pid
 * Method:    getPid
 * Signature: ()I
 */
JNIEXPORT jint JNICALL Java_Pid_getPid
  (JNIEnv *, jobject);

#ifdef __cplusplus
}
#endif
#endif

The C code that allows to get the current process ID:

#include <windows.h>
#include <stdio.h>
#include <iphlpapi.h>
#include "pid.h"

JNIEXPORT jint JNICALL Java_Pid_getPid
  (JNIEnv *env, jobject object) {
   return (int) GetCurrentProcessId();
}

I used cygwin to develop a Windows DLL from this in the following way:

gcc -mno-cygwin -I/usr/include -Ic:/jdk1.3.1/include -Ic:/jdk1.3.1/include/win32
 -shared Pid.c -Wl,--add-stdcall-alias -o Pid.dll

This DLL now allows you to get the process ID of your current Java app. Here’s an example:

C:experimentsjavapid>java Pid
3844
C:experimentsjavapid>java Pid
3876

For those who don’t have cygwin installed or want to start using it right away, here’s the library:

Pid.dll