Dheeraj Joshi
Dheeraj Joshi

Reputation: 3147

Exit hook for Java process

I am creating a TFTP server and keep it running using a infinite loop. When i try to send a kill signal

/bin/kill -s SIGINT <pid>

I want Java process to close TFTP server and exit.

class TFTP {
public void startTFTP(String str, String str1){
    try {
        //Start TFTP server
            // Both of below are not working.
            Runtime.getRuntime().addShutdownHook(new Thread(){
                @Override
                public void run(){
                    //Shutdown tftp server
                    System.out.println("Exiting");
                    System.exit(0);
                }
            });

            SignalHandler handler = new SignalHandler () {
                public void handle(Signal signal) {
                    System.exit(0);
                }
            };
            Signal.handle(new Signal("INT"), handler);
            Signal.handle(new Signal("TERM"), handler);

            while(true){
            // Infinite loop to keep process running.
            }
        }
    } catch (Exception e) {

    }
}
public static void main(String args[]){
        TFTP tftp = new TFTP();
        tftp.startTFTP(args[0],args[1]);
}

}

I kill the process from a script and calling

/bin/kill -s SIGINT <pid>

doesn't kill the java process for some reason. I thought SIGINT is handled as part of

Signal.handle(new Signal("INT"), handler);

What am i missing here?

Regards
Dheeraj Joshi

Upvotes: 1

Views: 3612

Answers (3)

Kush Sharma
Kush Sharma

Reputation: 86

I just read up:---SIGTERM is akin to asking a process to terminate nicely, allowing cleanup and closure of files. For this reason, on many Unix systems during shutdown, init issues SIGTERM to all processes that are not essential to powering off, waits a few seconds, and then issues SIGKILL to forcibly terminate any such processes that remain.

so u might need to use the SIGKILL also in the future for processes that are not essential to powering off.. u can check the process ids that need to be killed and try with the SIGTERM first and if some processes remain then use the SIGKILL. or as u said u can use the kill command first and kill -9 for the ones that u want to kill forcibly.

Upvotes: 1

maximdim
maximdim

Reputation: 8169

I think you need to sent 'SIGTERM' ('kill' w/o '-s' parameter) for shutdown hook to work.

Upvotes: 1

user507484
user507484

Reputation:

I would start the TFTP server in a new thread, and do a Thread.sleep(x) in the main thread. That way, the main thread can be interrupted.

Upvotes: 2

Related Questions