Mikhail
Mikhail

Reputation: 1613

How can I catch moment when someone kill java.exe process?

console java application. Someone kill java.exe process by Task Manager. How can I write to logs some information at this moment before application is terminated?

Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
    public void uncaughtException(Thread t, Throwable e) { ..... }
}); 

OR

Runtime.getRuntime().addShutdownHook(new Thread() {
    public void run() { ..... }
});

don't execute in such situation

Upvotes: 2

Views: 2871

Answers (5)

Alon
Alon

Reputation: 4952

you might try to start java.exe via a small naive (e.g. c++) application using a CreateProcess (in windows ) this application will then continue running monitoring the java process handle. if the java process is gone it can log it.

Upvotes: 2

MSalters
MSalters

Reputation: 180020

some practical solutions have already been suggested, but another is to ping-pong a "last status" message between 2 applications that monitor each other. When one dies, the other one writes the last received message to a log file. Users can't kill both processes quickly enough with Task Manager.

Upvotes: 3

Thomas Jung
Thomas Jung

Reputation: 33092

This is not possible. Shutdown hooks will only be executed in an orderly shutdown:

In rare circumstances the virtual machine may abort, that is, stop running without shutting down cleanly. This occurs when the virtual machine is terminated externally, for example with the SIGKILL signal on Unix or the TerminateProcess call on Microsoft Windows.

You can send another signal that will trigger an orderly shutdown like SIGINT. Killing a application should be the last resort after the application did not respond.

Upvotes: 6

Paul Tomblin
Paul Tomblin

Reputation: 182832

Give your users an orderly way to shut down the system, and tell them to stop using Task Manager to do so.

Upvotes: 1

Joonas Pulakka
Joonas Pulakka

Reputation: 36577

Some sort of solution is to write something to a log file all the time. This way you'll see whatever was the "last breath" of the Java program.

Upvotes: 2

Related Questions