Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gracefully shutdown a Java application that is terminated as a result of closing the command line from which it was executed?

There is a an answered question on Best Way to Gracefully Shutdown a Java Command Line Program. A shutdown hook does the job in case when a program was terminated by Ctrl+C.

My question is how to gracefully exit if the command line itself is closed during the execution of a Java program? I tested with shutdown hook but it didn't work in this case. I cannot find out what happens to the virtual machine in this scenario. Is the process and all its threads killed instantly? What kind of signal does closing command line produce?

So, how this particular problem can be solved?

EDIT: The problem concerns Windows environment.

like image 641
Limbo Exile Avatar asked Oct 31 '22 13:10

Limbo Exile


1 Answers

Logically, SIGHUP (terminal hangup) should be raised.

Actually, I've just checked my guess with a simple shell script. Yes, when a user closes a terminal emulator in which an application was started (and from which it wasn't detached), then the application receives SIGHUP. So set up a SIGHUP handler and react accordingly. A usual behaviour is to terminate an application, but your intents may be different.

Also if your Java application performs any STDIN/STDOUT operations, it should be closed or at least re-cofigured when HUP is received, because an attempt to read/write from non existing terminal would lead to SIGPIPE and/or program block.

For Windows take a look at Catch Windows terminal closing on running process

like image 195
user3159253 Avatar answered Nov 14 '22 10:11

user3159253