Skip to content

Instantly share code, notes, and snippets.

@mmcgrana
Created May 30, 2011 01:11
Show Gist options
  • Save mmcgrana/998316 to your computer and use it in GitHub Desktop.
Save mmcgrana/998316 to your computer and use it in GitHub Desktop.
(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