I have a bat script which runs a java application. If I press ctrl+c on it, it the application terminates gracefully, invoking all the shutdown hooks. However, if I just close the cmd window of the bat script, the shutdown hooks are never invoked.
Is there a way to solve this? Perhaps there’s a way to tell the bat script how to terminate the invoked applications when its window is closed?
From addShutdownHook documentation:
So i think nothing to do here, unfortunately.
CTRL-CLOSE signal in Windows Console. Seems non-tweakable.
Quoting above link:
ExitProcessto terminate the process.FALSE. If none of the registered handler functions returnsTRUE, the default handler terminates the process.TRUE. In this case, no other handler functions are called, and a pop-up dialog box asks the user whether to terminate the process. If the user chooses not to terminate the process, the system does not close the console until the process finally terminates.UPD. If native tweaks are acceptable for you, WinAPI
SetConsoleCtrlHandlerfunction opens way for suppressing of default behavior.UPD2. Revelations on Java signal handling and termination relatively old article, but section Writing Java signal handlers really may contain what you need.
UPD3.
I’ve tried Java signal handlers from article above. It works with
SIGINTnicely, but it not what we need, and i decided to carry it withSetConsoleCtrlHandler. The result is a bit complicated and may be not worth to implement in your project. Anyway, it could help someone else.So, the idea was:
CTRL+CLOSEsignal.Java code:
Native
replaceConsoleHandler:And handler itself:
And it works. In JNI code all error checks are omitted for clearance. Shutdown handler creates empty file
"d:\shutdown.mark"to indicate correct shutdown.Complete sources with compiled test binaries here.