Joe
Joe

Reputation: 1342

Java Process Termination - onEnd()?

When you force kill a process by PID:

kill -9 1123

Is there any method that is called when the process is terminated, that halts until shutdown?

Upvotes: 0

Views: 111

Answers (2)

kelgon
kelgon

Reputation: 401

For java, you can add a ShutdownHook to your process, when sigterm is send to this process, the code in ShutdownHook will be executed before jvm shuts itself down.

    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            //your cleanup codes
        }
    });

Upvotes: 2

Allan
Allan

Reputation: 12438

Have a look at the links to check the difference between both signals and how to trap them, etc.

In a nutshell, sigterm allows the process to clean his stuff (his last will) before the end but sigkill does not and can not be trapped by your application! (imagine programs running forever and unstoppable this would be a mess)

Additional readings:

Why I am not getting signal SIGKILL on kill -9 command in bash?

https://major.io/2010/03/18/sigterm-vs-sigkill/

http://www.learnlinux.org.za/courses/build/shell-scripting/ch12s03.html

Upvotes: 1

Related Questions