Java 使用“TERM”的信号处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1409165/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 11:45:57  来源:igfitidea点击:

Signal handling using "TERM"

javasignals

提问by chaithu

I have a standalone application in which I have to prompt the user with an confirm dialog box to save the changes made by him when he tries to shutdown the system by start-->shutdown.

我有一个独立的应用程序,当他尝试关闭系统时,我必须用确认对话框提示用户保存他所做的更改start-->shutdown

I came to know that by using signalhandlerswe can do it.
Can some one help me how to use signal handlers

我开始知道通过使用signalhandlers我们可以做到。
有人可以帮助我如何使用信号处理程序吗

采纳答案by VonC

Update May 2012 (2 and half years later)

2012 年 5 月更新(两年半后)

Trejkazcomments:

特雷卡兹评论:

On current versions of Java this signal handling code fails because the "INT" signal is "reserved by the VM or the OS".
Additionally, none of the other valid signal names actually fire when something requests the application to close (I just painstakingly tested all of the ones I could find out about...)
The shutdown hook mostly works but we find that in our case it isn't firing, so the next step is obviously to resort to registering a handler behind the JVM's back

在当前版本的 Java 上,此信号处理代码失败,因为“ INT”信号“由 VM 或操作系统保留”。
此外,没有其他的有效信号名称时要求的东西应用到实际接近火(我只是苦心测试了所有的人,我可以了解的......)
关闭挂接大部分工作,但我们发现,在我们的情况下,它的ISN不触发,所以下一步显然是诉诸于在 JVM 背后注册一个处理程序

The chapter "Integrating Signal and Exception Handling" of the "Troubleshooting Guide for HotSpot VM" mentions the signals "SIGTERM, SIGINT, SIGHUP" only for Solaris OS and Linux.
Only Exception Handling on Windows are mentioned.

HotSpot VM 故障排除指南”的“集成信号和异常处理”一章提到了仅适用于 Solaris OS 和 Linux的信号“ , , ”。 只提到了 Windows 上的异常处理。SIGTERMSIGINTSIGHUP



Original answer (Sept 2009)

原始答案(2009 年 9 月)

a ShutdownHookshould be able to handle that case

一个ShutdownHook应该能够处理这种情况

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        // what you want to do
    }
}));

(with caveats)
See also:

(有警告
另见:

as an illustration of simple signal handling:

作为简单信号处理的说明:

public class Aaarggh {
  public static void main(String[] args) throws Exception {
    Signal.handle(new Signal("INT"), new SignalHandler () {
      public void handle(Signal sig) {
        System.out.println(
          "Aaarggh, a user is trying to interrupt me!!");
        System.out.println(
          "(throw garlic at user, say `shoo, go away')");
      }
    });
    for(int i=0; i<100; i++) {
      Thread.sleep(1000);
      System.out.print('.');
    }
  }
}