Ctrl C-interrupts  in Java

Posted on 2000-04-16
Last Modified: 2008-02-20
how can i capture Ctrl- C interrupts in my console based java application.Is there a pure java solution or Jni has to be used .If Jni is the only way , pls do include a code snippet as i do not have much experience with C code .
Os : Solaris and Nt .

Question by:shhh

Expert Comment

ID: 2722309
just want to sign to receive mail notification of future comments or answers

Accepted Solution

fmaritato earned 200 total points
ID: 2723228
You have to write a signal handler in native C code to catch these events. Here are examples:

Windows NT:
BOOL WINAPI myHandler(DWORD ctrlType) {
  HWND window = NULL;
  printf("\n\n myHandler :: I caught exception!\n");

JNIEXPORT void JNICALL NativeCode_osw32catchCtrlC(JNIEnv *env, jclass obj){

JNIEXPORT void JNICALL NativeCode_setupControlC(JNIEnv *env, jclass obj) {
if (signal (SIGINT, sig_handler) == SIG_IGN)
    signal (SIGINT, SIG_IGN);
void sig_handler(int signum) {

  printf("Signal %d caught. Cleaning up...\n", signum);

LVL 19

Expert Comment

by:Jim Cakalic
ID: 2723344
There appear to be several possibilites for implementation:

1) Write a C/C++ program in which you register signal handlers before you start the JVM. Yuck.

2) Write a Java class and JNI for signal handling. A decent-looking general implementation of this (for Linux but appears to be platform independent) can be found at Another example can be found on the Java Developer Connection forums at

3) Use the undocumented sun.misc classes Signal and SignalHandler. Sun considers these classes part of its internal implementation and so does not document them as part of the the JDK. A Java program that directly calls any API in sun.* packages is not guaranteed to work on all Java-compatible platforms. In fact, such a program is not guaranteed to work even in future versions on the same platform. One side effect of this method is that there must be a thread dedicated to signal handling. Also, the author of this code indicates that this does not appear to work with the Hotspot VM as of 04-Apr-1999. Here is how this might look:

    // Installs Ctrl-C handler
    final Thread thread = Thread.currentThread();
    SignalHandler old = null;
    try {
        // HACK: Signal does not work with hotspot
        if (!System.getProperty("").equals("HotSpot VM")) {
            old = Signal.handle(new Signal("INT"), new SignalHandler() {
                public void handle(Signal sig) {
    } catch (IllegalArgumentException exc) {

    Object sync = new Object();
    synchronized (sync) {
        try {
            // Wait forever to be interrupted
        } catch (InterruptedException exc) {
            if (old != null) {
                Signal.handle(new Signal("INT"), old);
            // Here comes some cleanup of the application
I haven't personally validated any of these methods but I am interested in knowing more about this topic so I will assist with any problems.

Also, I will sound one warning about signal handling. In the research I did to answer this question, I came across a reference from the Java 2 SDK for Solaris Developer's Guide (page 41) stating, "Native code using JNI should not modify the signal processing state. The VM uses signals and any change to signal handling can result in VM failures." I don't have this guide (yet) so I am not sure whether this guidance applies to just Solaris or all Sun VMs.

Best regards,
Jim Cakalic
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.


Expert Comment

ID: 2723406
Well, my answer doesn't lock you in to using either method #1 or #2 according to mister Cakalic's comment. In either case you need to set up the signal handler in order to catch events. Whether you wrap it around a Java class specifically for use with signal processing is irrelevent. My example illustrates which system functions you will need to use.

As for the third suggestion, I would strongly recommend you don't rely on undocumented/unsupported classes for your program if it is to be used in a real product of some sort that will be sold.  This is one of the first rules of software development.

Good luck.
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2723423
The research continues...

Another package which provides some signal handling capability for Java based on the POSIX specification:

Jim Cakalic
LVL 19

Expert Comment

by:Jim Cakalic
ID: 2723534
Well ... actually ... the posted code would appear to be an example of method #2 because you use JNI to access a native library.

As for "Whether you wrap it around a Java class specifically for use with signal processing is irrelevent", I would tend to disagree. From a design perspective, I would think that you would want to encapsulate and isolate this behavior to hide the implementation and provide a point for extension. From an implementation perspective, and correct me if I am wrong, I understood the Java mangling of native method names was:

    "Java_" + package "_" + class + "_" + method

Because the package and class are a required part of the JNI declaration, the choice made as to which class will be allocated this behavior becomes highly relevant. Since the poster admits a lack of familiarity with C code (and we can then surmise little familiarity with JNI),

Finally, perhaps the fact that I only provided an example for using the sun.misc packages was misleading. I completely agree that using these undocumented packages is not a preferred solution. However, I felt that it I should mention it as a matter of completeness. Because I have seen others recommend it, and could anticipate that it might be raised in this topic, my discussing it gave me an opportunity to provide the necessary warning about consequences of this choice. Given that Java platform source code is now freely available, these classes _might_ also serve as a reasonable source of ideas for a custom implementation.

Best regards,
Jim Cakalic

Author Comment

ID: 2724898
Tanx a lot .....Got the perfect answer .The comments were also more than useful .

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

708 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now