In a command line / JVM app (with coroutines), how...
# getting-started
k
In a command line / JVM app (with coroutines), how to listen for SIGTERM and do some cleanup?
Copy code
fun main() = runBlocking {
    // ... launch some stuffs
    // wait for ctrl-C, how?
    cleanup()
    cancel()
}
r
You can add a shutdown hook:
Copy code
Runtime.getRuntime().addShutdownHook(
    object : Thread() {
      override fun run() {
        cleanup()
        cancel()
      }
    }
  )
With a CountDownLatch you can optionally move the cleanup back into main:
Copy code
fun blockUntilShutdown(
  gate: Gate = Gate.closed()
) {
  val gate = CountDownLatch(1)
  val runningThread = Thread.currentThread()

  Runtime.getRuntime().addShutdownHook(
    object : Thread() {
      override fun run() {
        gate.countDown()
        runningThread.join()
      }
    }
  )

  gate.await()
}

fun main() = runBlocking {
    // ... launch some stuffs
    blockUntilShutdown()
    cleanup()
    cancel()
}
Not sure how that all plays with coroutines, mind you…
🙏 1
If you actually want to handle specific signals you can have a look at `sun.misc.Signal`:
Copy code
Signal.handle(Signal("INT")) { signal ->
  println("handling $signal")
}
but obviously depending on the
sun.misc
package is suboptimal, not being part of the standard.
🙏 1