?
Solved

Ctrl C-interrupts  in Java

Posted on 2000-04-16
7
Medium Priority
?
2,035 Views
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 .

0
Comment
Question by:shhh
7 Comments
 
LVL 3

Expert Comment

by:ovidiucraciun
ID: 2722309
just want to sign to receive mail notification of future comments or answers
0
 
LVL 1

Accepted Solution

by:
fmaritato earned 800 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");
  exit(0);
}

JNIEXPORT void JNICALL NativeCode_osw32catchCtrlC(JNIEnv *env, jclass obj){
   SetConsoleCtrlHandler(myHandler,TRUE);
}
------------------------
Solaris:

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);
  fflush(stdout);

  exit(1);
}
0
 
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 http://interstice.com/~kevinh/projects/javasignals/. Another example can be found on the Java Developer Connection forums at http://forum2.java.sun.com/forum?14@@.ee77e26.

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("java.vm.name").equals("HotSpot VM")) {
            old = Signal.handle(new Signal("INT"), new SignalHandler() {
                public void handle(Signal sig) {
                    thread.interrupt();
                }
            });
        }
    } catch (IllegalArgumentException exc) {
    }

    Object sync = new Object();
    synchronized (sync) {
        try {
            // Wait forever to be interrupted
            sync.wait();
        } 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
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 1

Expert Comment

by:fmaritato
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.
0
 
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:
http://www.bmsi.com/java/posix/posix.html

Jim Cakalic
0
 
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
0
 

Author Comment

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

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month16 days, 20 hours left to enroll

862 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