Modify Control C Command Signal to Allow Input

247 views Asked by At

Upon pressing Control C on the command prompt, is there a possibility of interrupting this signal, and prompting the user for input, to confirm they want to exit the program? I am aware that there are signal interrupts, but not on how to modify the signal to allow input.

String user;
Scanner input = new Scanner(System.in);

try {
      [...] // Some code
    }
catch(NoSuchElementException e) {
 System.out.println("You have chosen to exit the program using Control C.\n");
 System.out.print("Are you sure you want to exit? Type Yes or No.");
 user = input.nextLine();
 if(user.equals("yes")) {
    System.exit(0);
 }
 else { 
  [...] // Return to the main menu
 }

Currently, this code catches the Control C signal, outputs the String: "Are you sure you want to exit? [..]" but then refuses to accept input from the user. It waits a second, then the program would exit instead of getting the input from the user to confirm their decision.

However, I want the code to request input from the user upon Control C activation, and if it is yes, exit the program, else return to the main menu, which it seems to not work as intended.

1

There are 1 answers

2
K Erlandsson On

The short answer is: You should really not do that. There is no portable way to prevent an interrupt signal from exiting a Java application.

The longer answer is that might be possible using internal classes such as sun.misc.Signal and sun.misc.SignalHandler. Since these classes are not portable across JVM implementations and may change in later versions you should avoid using them.

What you should do is to provide another standard way of exiting the application such as typing quit and require confirmation when receiving that input.

If you really want to avoid users exiting with ctrl+c you could try running java with -Xrs which should disable the handling of the console signal (NB: I have not tested this and am not really sure how it works)