Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win


Ctrl C-interrupts  in Java

Posted on 2000-04-16
Medium Priority
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
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

Expert Comment

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

Accepted Solution

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");

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 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) {
    } 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
Industry Leaders: 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!


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

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

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
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

636 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