Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handle if a process killed externally

I am writing a program where i am creating multiple threads in a process.

I need to handle that if the process is killed externally by someone by using kill -9 signal or Ctrl + C, my program should do some action before closing e.g. it should change the status of process to aborted in database.

How can i handle that ?

Do i need addShutdownHook() ? or is there any other better solution to my problem ?

I have added :

Runtime.getRuntime().addShutdownHook( new Thread() {

            @Override
            public void run() {
                logger.info( "Running Shutdown Hook" );
                //call some method
                System.out.println( "Running Shutdown Hook" );
            }
        } );

inside my main method, But it doesn't seem to work.

like image 542
chumak Avatar asked Oct 30 '22 15:10

chumak


1 Answers

Short answer: probably won't work.

See JavaDoc for that addShutdownHook():

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... If the virtual machine aborts then no guarantee can be made about whether or not any shutdown hooks will be run.

In other words: a shutdown hook is not a robust choice to address your requirements.

like image 152
GhostCat Avatar answered Nov 09 '22 08:11

GhostCat