java 捕捉訊號(linux下的kill,ctrl+c)

來源:互聯網
上載者:User

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.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.