我正在创建一个 TFTP 服务器并使用无限循环使其保持运行。当我尝试发送终止信号时
/bin/kill -s SIGINT <pid>
我希望 Java 进程关闭 TFTP 服务器并退出。
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]);
}
我从脚本中终止进程并调用
/bin/kill -s SIGINT <pid>
由于某种原因不会终止 java 进程。我认为 SIGINT 是作为
的一部分处理的Signal.handle(new Signal("INT"), handler);
我在这里错过了什么?
问候
迪拉吉·乔希
最佳答案
我会在一个新线程中启动 TFTP 服务器,然后在主线程中执行 Thread.sleep(x)。这样,主线程就可以被中断。
关于java - Java进程的退出钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9996370/