import sun.misc.Signal;<br />import sun.misc.SignalHandler;</p><p>/***<br />* java訊號處理demo<br />* @author jiang_qh<br />*<br />*/<br />public class SignalHandlerExample implements SignalHandler{</p><p>private SignalHandler oldHandler;</p><p>public void handle(Signal signal) {<br /> System.out.println("Signal handler called for signal "<br /> + signal);<br /> try {</p><p> signalAction(signal);</p><p> // Chain back to previous handler, if one exists<br /> if (oldHandler != SIG_DFL && oldHandler != SIG_IGN) {<br /> oldHandler.handle(signal);<br /> }</p><p> } catch (Exception e) {<br /> System.out.println("handle|Signal handler"<br /> +"failed, reason " + e.getMessage());<br /> e.printStackTrace();<br /> }<br />}</p><p>public void signalAction(Signal signal) {</p><p> System.out.println("Handling " + signal.getName());<br /> System.out.println("Just sleep for 5 seconds.");<br /> try {<br /> Thread.sleep(5000);<br /> } catch (InterruptedException e) {<br /> System.out.println("Interrupted: "<br /> + e.getMessage());<br /> }<br />}</p><p>public static SignalHandler install(String signalName) {<br /> Signal diagSignal = new Signal(signalName);<br /> SignalHandlerExample instance = new SignalHandlerExample();<br /> instance.oldHandler = Signal.handle(diagSignal, instance);<br /> return instance;<br /> }</p><p>public static void main(String[] args) {</p><p> //kill命令<br /> SignalHandlerExample.install("TERM");<br /> //ctrl+c命令</p><p> SignalHandlerExample.install("INT");</p><p> System.out.println("Signal handling example.");<br /> try {<br /> Thread.sleep(50000);<br /> } catch (InterruptedException e) {<br /> System.out.println("Interrupted: " + e.getMessage());<br /> }</p><p> }</p><p>}<br />
在linux上運行該程式。然後kill掉其pid,列印:
Signal handling example.
Signal handler called for signal SIGTERM
Handling TERM
Just sleep for 5 seconds.
[dispatch@localhost ThirdTest]$ sh signal.sh
Signal handling example.
Signal handler called for signal SIGTERM
Handling TERM
Just sleep for 5 seconds.