0

Possible Duplicate:
Java: How could I “intercept” Ctrl+C in a CLI application?

On Windows I start a java non gui application doing a task Then press CNTL-C and the program just exits, none of my interrupt handling code seems to trigger, even putting a try/catch in the main method never displays a stack trace to indicate it has been interuppted.

public static void main(final String[] args) throws Exception
{
    try
    {
         CmdLineDecoder cld = new CmdLineDecoder();
         cld.start(args);
         System.exit(0);
    }
    catch(Exception e)
    {
         e.printStackTrace();
        throw e;
    }
}

I'm clearly misunderstanding the effect of Cntl-C, but what ?

Community
  • 1
  • 1
Paul Taylor
  • 13,411
  • 42
  • 184
  • 351
  • Does `CmdLineDecoder.start` throw an `InterruptedException`? – Jeffrey Aug 22 '12 at 22:14
  • But what ... what? Did you mean to close like that? – Gray Aug 22 '12 at 22:14
  • http://stackoverflow.com/questions/1216172/java-how-could-i-intercept-ctrlc-in-a-cli-application – jtoberon Aug 22 '12 at 22:17
  • @Jeffrey no doesn't seem to because should output a System.out.println message if recewives such an exception – Paul Taylor Aug 22 '12 at 22:17
  • Seems like this is a dup, so it would be more constructive to vote up the answer on http://stackoverflow.com/questions/1216172/java-how-could-i-intercept-ctrlc-in-a-cli-application. – jtoberon Aug 22 '12 at 22:20

1 Answers1

2

You can't do general signal handling in java, but you can handle Ctrl-c.

If you need to do something upon VM shutdown, use a shutdown hook: Runtime.addShutdownHook.

From the docs:

The Java virtual machine shuts down in response to two kinds of events:

The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

I've used this in the past on Windows/OSX.

Community
  • 1
  • 1
pb2q
  • 58,613
  • 19
  • 146
  • 147