Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Possible to disable Ctrl-C in Java console application?

Tags:

java

As the subject states, is there a way to disable CTRL-C (and other signals) so that they don't terminate the application?

like image 973
Jin Kim Avatar asked Mar 14 '12 16:03

Jin Kim


2 Answers

EDIT2: this may also help: Capture SIGINT in Java

This and this appear to be what you want.

Ctrl-C and other command send "signals" to your program, and if you write code to "catch" catch those signals, you can change how your program reacts. Ideally, you would want ctrl-c to terminate the program, as it's what the user expects, so keep in mind that you should tell the user why it's not terminating if you change the program's response.

Edit3: Cat's suggestion of a keylistener is your next best bet if you can't catch and dismiss the event yourself. Halway down the page is an example of how to do it for java in linux/Windows - it's not a portable thing. Essentially, your program will be handling keyboard events instead of the console sending the keybaord events to it. This means the command line is bypassed, and cannot read the ctrl-c call. I'd write code, but I'm at work now; Wednesdays are a long day for me. If you haven't gotten it by the time I get home, I'll take a look at writing some examples.

like image 144
Marshall Conover Avatar answered Sep 20 '22 17:09

Marshall Conover


You need to use a SignalHandler to intercept the SIGINT signal triggered by a CTRL-C. The CTRL-C will be handled at the OS level assuming you don't want the VM to receive the signal.

IBM DeveloperWorks has an article on doing this - http://www.ibm.com/developerworks/ibm/library/i-signalhandling/?open&l=409,t=grj,p=jsh

Oracle link - http://www.oracle.com/technetwork/java/javase/signals-139944.html

like image 45
wafflemkr Avatar answered Sep 17 '22 17:09

wafflemkr