Skip to Main Content

Java HotSpot Virtual Machine

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Calling a kill-signal hook in Windows

843829May 20 2005 — edited May 23 2005
Hi,

I'm trying to write a JNI hook in Windows to receive messages when the user shuts down the JVM, say with a Ctrl+C, or by shutting down Windows. Here's my native code:
///////////////////////////////////////////////
jobject shutdownHook;  //both these are set in the
JavaVM* jvm; //JNI entry method

//the method receiving kill signals
BOOL WINAPI HandlerRoutine(DWORD dwCtrlType) {
  JNIEnv* env;
  jvm->AttachCurrentThread((void **) &env, NULL);
  if (shutdownHook != NULL) { 
	  jmethodID mid; 
	  jclass cl = env->FindClass("java/lang/Runnable");
	  mid = env->GetMethodID(cl, "run", "()V");
	  env->CallVoidMethod(shutdownHook, mid);
	  ::MessageBox(NULL, "Got there", "Got There", MB_OK);//for debug porpoises
  }
  return FALSE;
}

JNIEXPORT void JNICALL Java_main_Shutdown_registerShutdownHook
  (JNIEnv * env, jclass, jobject hook) {
	env->GetJavaVM(&jvm);
	shutdownHook = hook;
	SetConsoleCtrlHandler(HandlerRoutine, TRUE);//Win32 API
}
///////////////////////////////////////////////
And the Java defintion, plus an example Java program using it:
///////////////////////////////////////////////
class Shutdown {
  static {
    System.loadLibrary("ShutdownHook");
  }
  public static native void registerShutdownHook(Runnable sh);
}

class Test {
  public static void main(String[] args) throws Exception {
    Shutdown.registerShutdownHook(new Runnable() {
      public void run() {
        System.out.println("PANG!");
      }
    });
    Thread.sleep(60000);
  }
}
///////////////////////////////////////////////
Everything seems to work fine--my native handler method gets the signal, finds the appropriate class, successfully calls the method, and displays the message box. But as far as I can tell, the method on the Java side isn't called...it doesn't print anything out, and other tests have also shown that the method isn't being called.

I'm a relative newbie to JNI...anyone see what I'm doing wrong?

Thanks,

Walter Gildersleeve
Freiburg, Germany

P.S. I'm testing this on WinXP sp2, with JDK 1.4.2_05-b04, native code built with MS VisualStudios 6.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jun 20 2005
Added on May 20 2005
6 comments
479 views