概述
import sun.misc.Signal;
import sun.misc.SignalHandler;
public class SignalHandlerExample implements SignalHandler {
private SignalHandler oldHandler;
public static SignalHandler install(String signalName) {
Signal diagSignal = new Signal(signalName);
SignalHandlerExample instance = new SignalHandlerExample();
instance.oldHandler = Signal.handle(diagSignal, instance);
return instance;
}
public void handle(Signal signal) {
System.out.println("Signal handler called for signal "
+ signal);
try {
signalAction(signal);
// Chain back to previous handler, if one exists
if (oldHandler != SIG_DFL && oldHandler != SIG_IGN) {
oldHandler.handle(signal);
}
} catch (Exception e) {
System.out.println("handle|Signal handler
failed, reason " + e.getMessage());
e.printStackTrace();
}
}
public void signalAction(Signal signal) {
System.out.println("Handling " + signal.getName());
System.out.println("Just sleep for 5 seconds.");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("Interrupted: "
+ e.getMessage());
}
}
public static void main(String[] args) {
SignalHandlerExample.install("TERM");
SignalHandlerExample.install("INT");
SignalHandlerExample.install("ABRT");
System.out.println("Signal handling example.");
try {
Thread.sleep(50000);
} catch (InterruptedException e) {
System.out.println("Interrupted: " + e.getMessage());
}
}
}
This program handles the TERM, INT, and ABRT signals. When it starts up, it will justsleep. During this time, if you press Ctr-C, the INT signal is triggered and signalAction is called.
Here is the sample output.
C:>java -cp . SignalHandlerExample Signal handling example. Signal handler called for signal SIGINT Handling INT Just sleep for 5 seconds.
最后
以上就是仁爱墨镜为你收集整理的Singal和SingalHandler用法的全部内容,希望文章能够帮你解决Singal和SingalHandler用法所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复