Skip to content

Instantly share code, notes, and snippets.

@mmcgrana mmcgrana/handle.clj
Created May 30, 2011

Embed
What would you like to do?
(ns demo.handle
(:import (sun.misc Signal SignalHandler)))
(defn trap-signal [sig f]
(Signal/handle (Signal. sig)
(proxy [SignalHandler] []
(handle [_] (f)))))
(defn trap-shutdown [f]
(let [rt (Runtime/getRuntime)]
(.addShutdownHook rt
(Thread. ^Runnable f))))
(defn -main [& args]
(if (= (first *command-line-args*) "signal")
(do
(println "trapping signal")
(trap-signal"TERM"
(fn []
(println "signaled")
(Thread/sleep 3000)
(println "exiting")
(System/exit 0))))
(do
(println "trapping shutdown")
(trap-shutdown
(fn []
(println "shutting down")
(Thread/sleep 3000)
(println "exiting")))))
(println "awaiting termination")
(Thread/sleep 100000))
; $ lein trampoline run -m demo.handle signal
; trapping signal
; awaiting termination
; $ kill -TERM pid
; signaled
; exiting
; $ echo $?
; 0
;
; $ lein trampoline run -m demo.handle shutdown
; trapping shutdown
; awaiting termination
; $ kill -TERM pid
; shutting down
; exiting
; $ echo $?
; 143
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.