4

In a Java console application, I would like to handle Ctrl+C by printing:

Do you really want to exit (y,N)?

Terminate normally when 'y' is pressed but continue running if anything else is pressed.

Is this possible in Java?

Original

I know how to shutdown Java application gracefully by adding shutdown hook, or how to handle signals like interrupt or TERM.

The problem here is, in C, when I handle the interrupt I can force the app to exit or to just print a message and continue working. I want to do something like this. When you press Ctrl+C, I ask you do you really want to exit (y,n).

However, in Java I see that all I can do is write something before exiting, so I will always exit no matter what. What is the solution to this problem?

Jan Nielsen
  • 10,892
  • 14
  • 65
  • 119
  • [Similar](https://stackoverflow.com/questions/3250280/ignore-sigint-in-java) [question](https://stackoverflow.com/questions/2975248/how-to-handle-a-sigterm), though since neither of those seems to provide a working *solution*, I wouldn't dare close this as a dup of either. – Silvio Mayolo May 05 '22 at 16:12
  • 2
    This isn't really so much a problem with java as with the way you are running it / the console. Java run as a background service for example doesn't have this issue. You just need a better replacement for the console – ControlAltDel May 05 '22 at 16:15
  • I want to know if there is way to achieve this as a java console program or it's impossible... – hikaru jakafura May 05 '22 at 16:37
  • In Python you can catch `KeyboardInterrupt` and your program can keep going; it's not clear why Java fundamentally cannot do the same thing, but it does seem that it cannot. (At most you can register a shutdown hook, but you can't stop the program from shutting down.) – kaya3 Nov 09 '22 at 17:09

1 Answers1

1

You can run the java application as a background process by using the & in the end of the command.

This way the CTRL + C in your command line will not force the application to exit and you can still execute other commands in your command line tool.

#!/bin/sh
java -jar myApp.jar & 
Panagiotis Bougioukos
  • 15,955
  • 2
  • 30
  • 47
  • 1
    I'm sorry but this have nothing to do with my question... I'm not asking for how to run an application in the background... I'm asking is there a way (in java) to ignore the interrupt signal while interacting with the program... when you send it to the background then you aren't going to interact with it (like asking your name, your age... after performing some manipulations [<-example]) I could do it with C language or c++... but I need to know if it's possible in java, not how to work around it... – hikaru jakafura May 06 '22 at 22:32