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
Netscaler Common Configuration How To guides

If you use NetScaler you will want to see these guides. The NetScaler How To Guides show administrators how to get NetScaler up and configured by providing instructions for common scenarios and some not so common ones.


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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Protect jar file - windows app 2 53
groupNoAdj 7 96
JUnit 4 @Before and @BeforeClass differences 3 59
how do i compare an object based on two fields 6 54
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
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 how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

777 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