如何正常关闭由于关闭从其执行的命令行而终止​​的Java应用程序? [英] How to gracefully shutdown a Java application that is terminated as a result of closing the command line from which it was executed?

查看:457
本文介绍了如何正常关闭由于关闭从其执行的命令行而终止​​的Java应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最佳方法有一个已回答的问题以正常关闭Java命令行程序。当程序被Ctrl + C终止时,关闭挂钩会执行作业。



我的问题是如何在执行期间关闭命令行本身时如何正常退出的Java程序?我测试与关闭挂钩,但它没有在这种情况下工作。我不知道在这种情况下虚拟机发生了什么。进程及其所有线程是否即刻死亡?
关闭命令行产生什么样的信号?



那么,这个特殊的问题可以如何解决?



编辑:问题与Windows环境有关。

解决方案

逻辑上,SIGHUP p>

其实,我只是用一个简单的shell脚本检查了我的猜测。是的,当用户关闭应用程序已启动(并且未从其中分离)的终端仿真器时,应用程序将收到SIGHUP。所以设置一个SIGHUP处理程序并作出相应的反应。通常的行为是终止应用程序,但您的意图可能不同。



此外,如果您的Java应用程序执行任何STDIN / STDOUT操作,它应该关闭或至少在接收到HUP时重新配置,因为尝试从非现有终端读/写将导致SIGPIPE和/或程序块。



对于Windows,请查看在正在运行的进程上捕获Windows终端正在关闭


There is a an answered question on Best Way to Gracefully Shutdown a Java Command Line Program. A shutdown hook does the job in case when a program was terminated by Ctrl+C.

My question is how to gracefully exit if the command line itself is closed during the execution of a Java program? I tested with shutdown hook but it didn't work in this case. I cannot find out what happens to the virtual machine in this scenario. Is the process and all its threads killed instantly? What kind of signal does closing command line produce?

So, how this particular problem can be solved?

EDIT: The problem concerns Windows environment.

解决方案

Logically, SIGHUP (terminal hangup) should be raised.

Actually, I've just checked my guess with a simple shell script. Yes, when a user closes a terminal emulator in which an application was started (and from which it wasn't detached), then the application receives SIGHUP. So set up a SIGHUP handler and react accordingly. A usual behaviour is to terminate an application, but your intents may be different.

Also if your Java application performs any STDIN/STDOUT operations, it should be closed or at least re-cofigured when HUP is received, because an attempt to read/write from non existing terminal would lead to SIGPIPE and/or program block.

For Windows take a look at Catch Windows terminal closing on running process

这篇关于如何正常关闭由于关闭从其执行的命令行而终止​​的Java应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆