Solved

Ctrl C-interrupts  in Java

Posted on 2000-04-16
7
1,911 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 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");
  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
The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

 
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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
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.

695 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