4

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?

Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
  • [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

1 Answers1

2

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
  • 10,173
  • 2
  • 13
  • 29
  • 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 [ – hikaru jakafura May 06 '22 at 22:32