从命令行运行groovy脚本时是否可以侦听CTRL C?
我有一个创建一些文件的脚本.如果中断我想从磁盘中删除它们然后终止.
可能?
更新1:
源于@tim_yates答案:
def withInteruptionListener = { Closure cloj,Closure onInterrupt ->
def thread = { onInterrupt?.call() } as Thread
Runtime.runtime.addShutdownHook (thread)
cloj();
Runtime.runtime.removeShutdownHook (thread)
}
withInteruptionListener ({
println "Do this"
sleep(3000)
throw new java.lang.RuntimeException("Just to see that this is also taken care of")
},{
println "Interupted! Clean up!"
})
解决方法
以下应该有效:
CLEANUP_REQUIRED = true
Runtime.runtime.addShutdownHook {
println "Shutting down..."
if( CLEANUP_REQUIRED ) {
println "Cleaning up..."
}
}
(1..10).each {
sleep( 1000 )
}
CLEANUP_REQUIRED = false
正如您所看到的,(正如@DaveNewton指出的那样),当用户按下CTRL-C或者进程正常结束时,将打印“关闭…”,因此您需要一些方法来检测是否需要清理
更新
为了好奇,以下是使用不受支持的sun.misc类的方法:
import sun.misc.Signal
import sun.misc.SignalHandler
def oldHandler
oldHandler = Signal.handle( new Signal("INT"),[ handle:{ sig ->
println "Caught SIGINT"
if( oldHandler ) oldHandler.handle( sig )
} ] as SignalHandler );
(1..10).each {
sleep( 1000 )
}
但显然,这些类不能被推荐,因为它们可能会消失/改变/移动
