By Alvin Alexander. Last updated: November 15, 2020
As a brief note about catching the [ctrl][c]
/ctrl-c
signal in a Scala command-line application, I just used this approach on Mac (Unix) system, and was able to catch the ctrl-c
signal:
/**
* The ability to cancel this code with `ctrl-c` inside of
* sbt requires you to have this setting in build.sbt:
*
* fork in run := true
*/
object SlowSocketServer extends App {
val serverResponseDelayTimeMs = 0
val serverPort = 5150
Runtime.getRuntime().addShutdownHook(new Thread {
override def run = {
System.out.println("Shutdown hook ran")
// if (socket != null) socket.close()
Thread.sleep(1000)
}
})
// more code here ...
I was running this application with sbt, and as long as I used that fork
setting in the build.sbt file, the ctrl-c
keystroke killed my application without also killing sbt, which is what I wanted. This method also printed out the "Shutdown hook ran"
string before it died, as desired.