1

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

Dheeraj Joshi
  • 3,057
  • 8
  • 38
  • 55
  • Have you seen http://stackoverflow.com/questions/2541475/capture-sigint-in-java ? – Sam DeHaan Apr 03 '12 at 15:22
  • Yes i did Googling and search old StackOverFlow threads. But kill -2 is also not working for me. So i was wondering i guess i did some basic mistake. – Dheeraj Joshi Apr 03 '12 at 15:28

3 Answers3

2

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.

1

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

maximdim
  • 8,041
  • 3
  • 33
  • 48
1

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.