Search code examples
javajarraspberry-pishutdown-hook

Raspberry Pi Java Shutdown hook


I have a Raspberry Pi running Java 1.8.0 and a file called test.jar. When I run the code and then stop the program with Ctrl+Z the Shutdown hook does not run but when I run the code on windows and stop it, the shutdown hook will work.

How can I fix this, Thanks

public class Test
{
    public static void main(String[] args)
    {
        Runtime.getRuntime().addShutdownHook(new Thread()   //Add shutdown code
        {
            public void run()
            {
                System.out.println("Shutdown");
            }
        });

        while(true) { }
    }
}

Solution

  • In a linux terminal, ctrl-z sends a SIGSTOP to the foreground process. This is one of two signals (the other being SIGKILL) that you cannot handle in your process. That means that java has no way to run any code in response to the signal.

    However, SIGSTOP doesn't end the process anyway, it simply pauses it. You can continue it by sending a SIGCONT signal, which can be achieved in your shell by using the fg command.

    Try using ctrl-c instead to end your program, and it ought to work (since that will send a SIGINT instead, which can be handled).