Java – listen for Ctrl C

Can I listen to Ctrl C when running groovy scripts from the command line?

I have a script to create some files If I interrupt, I want to delete them from the disk and terminate

probably?

Update 1: from @ Tim_ Yates answer:

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!"
})

Solution

The following shall be valid:

CLEANUP_required = true
Runtime.runtime.addShutdownHook {
  println "Shutting down..."
  if( CLEANUP_required ) {
    println "Cleaning up..."
  }
}
(1..10).each {
  sleep( 1000 )
}
CLEANUP_required = false

As you can see, (as @ Dave Newton pointed out), when the user presses ctrl-c or the process ends normally, "close..." will be printed, so you need some methods to detect whether cleaning is needed

to update

For curiosity, the following is using an unsupported sun Methods of misc class:

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 )
}

But obviously, these classes cannot be recommended because they may disappear / change / move

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>