https://kotlinlang.org logo
#getting-started
Title
# getting-started
k

knthmn

09/25/2021, 4:57 AM
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

Rob Elliot

09/25/2021, 10:06 AM
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
4 Views