如何在Clojure中捕获CTRL + C? [英] How to catch CTRL+C in Clojure?

查看:197
本文介绍了如何在Clojure中捕获CTRL + C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的单线程Clojure程序,它创建一个用于交换数据的临时文件。当程序正常退出时,此文件被删除,但是当程序通过 Ctrl + C Ctrl + < kbd>或 Ctrl + Z 代码的位从不执行。我需要它执行方面sof如何程序退出。我知道我需要捕获这个信号(我以前在其他语言中做过),但我似乎不知道如何在Clojure中做。

I have a simple single threaded Clojure program that creates a temp file for swapping data. When the program exits normally this file is deleted, however when the program is exited via Ctrl+C, Ctrl+D, or Ctrl+Z that bit of code never executes. I need it to execute regardles sof how the program exits. I know that I need to catch that signal (I've done this before in other languages), but I can't seem to figure out how to do it in Clojure.

推荐答案

我不知道Clojure是否有包装方法。在Java中,您可以使用 Runtime.addShutdownHook()

I don't know if Clojure has wrapped method for that purpose. In java, you can use Runtime.addShutdownHook()


注册新的虚拟机关机挂钩。

Registers a new virtual-machine shutdown hook.

Java虚拟机响应两种事件而关闭:

The Java virtual machine shuts down in response to two kinds of events:


  • 程序退出正常,当最后一个非守护线程退出或者退出(等效于System.exit)方法被调用时,或

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or

虚拟机终止响应

的用户中断,例如键入^ C或系统范围的事件,例如用户注销或系统关闭。

更新



这是一个简单的演示

Update

Here is a simple demo

(.addShutdownHook (Runtime/getRuntime) (Thread. (fn [] (println "Shutting down..."))))

user=> ;; Ctrl-C
Shutting down...

这篇关于如何在Clojure中捕获CTRL + C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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