Let’s assume we have the following main function
suspend fun main() = supervisorScope {
while (isActive) {
delay(1000)
println("Running...")
}
}
How can I cancel the coroutine when the jvm receives a SIGINT signal?
My first approach was this
suspend fun main() = supervisorScope {
Signal.handle(Signal("INT")) {
this.cancel()
}
while (isActive) {
delay(1000)
println("Running...")
}
}
which correctly cancels the main coroutine and all their children. But unfortunately the jvm terminates with a kotlinx.coroutines.JobCancellationException exception and exit code 1 instead of exit code 0. So I tried this
suspend fun main() = try {
supervisorScope {
Signal.handle(Signal("INT")) {
this.cancel()
}
while (isActive) {
delay(1000)
println("Running...")
}
}
} catch (e: CancellationException) {
//ignore exception
}
but the ignored exception is ugly.
Do you have another idea?