How to catch CTRL+C in Clojure?

喜夏-厌秋 提交于 2019-12-03 08:56:27

问题


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.


回答1:


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.

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

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

  • The virtual machine is terminated in response to a user interrupt, such as typing ^C, or a system-wide event, such as user logoff or system shutdown.

Update

Here is a simple demo

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

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



回答2:


Have a look at the deleteOnExit method in the java.io.File:

(import '(java.io File))
(doto (File/createTempFile "foo" nil nil) (.deleteOnExit))


来源:https://stackoverflow.com/questions/11709639/how-to-catch-ctrlc-in-clojure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!