假设我们有一个用 java 编写的简单的守护进程:
public class Hellow {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
while(true) {
// 1. do
// 2. some
// 3. important
// 4. job
// 5. sleep
}
}
}
我们使用start-stop-daemon
它来守护它,默认情况下发送SIGTERM
(TERM)信号--stop
假设当前执行的步骤是#2。而此时我们正在发送 TERM 信号。
发生的情况是执行立即终止。
我发现我可以使用处理信号事件,addShutdownHook()
但问题是它仍然会中断当前执行并将控制权传递给处理程序:
public class Hellow {
private static boolean shutdownFlag = false;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
registerShutdownHook();
try {
doProcessing();
} catch (InterruptedException ex) {
System.out.println(ex);
}
}
static private void doProcessing() throws InterruptedException {
int i = 0;
while(shutdownFlag == false) {
i++;
System.out.println("i:" + i);
if(i == 5) {
System.out.println("i is 5");
System.exit(1); // for testing
}
System.out.println("Hello"); // It doesn't print after System.exit(1);
Thread.sleep(1000);
}
}
static public void setShutdownProcess() {
shutdownFlag = true;
}
private static void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("Tralala");
Hellow.setShutdownProcess();
}
});
}
}
所以,我的问题是 - 是否有可能不中断当前执行,而是TERM
在一个单独的线程中处理信号(?),以便我能够设置shutdown_flag = True
以便循环main
有机会优雅地停止?