pgreze
08/03/2021, 9:00 AMephemient
08/03/2021, 9:18 AMsuspend fun process(vararg command: String) = suspendCancellableCoroutine { continuation ->
val process = ProcessBuilder(*command).start()
continuation.invokeOnCancellation { process.destroy() }
continuation.resume(process.waitFor()) { }
}
Nick Allen
08/03/2021, 5:24 PMrunInterruptible
can help break out of blocking methods like Process.waitFor
pgreze
08/04/2021, 1:57 AMephemient
08/04/2021, 2:05 AMrunInterruptible
is pretty similar and also throws a InterruptedException
which can help break out of some blocking functions (such as waitFor
).destroy()
will cause .waitFor()
to finish anywayrunInterruptible
would look something like this:
suspend fun process(vararg command: String): Int {
val process = ProcessBuilder(*command).start()
try {
return runInterruptible {
process.waitFor()
}
} finally {
process.destroy()
}
}
pgreze
08/04/2021, 2:50 AMinvokeOnCancellation
seems what I need but always good to know the alternatives 🙂invokeOnCancellation
but I could not use awaitAll
inside, and everything I tried were just more verbose alternatives of my runInterruptible
experiment.
If you don’t mind reviewing it, here is my current working code: https://github.com/pgreze/kotlin-process/pull/7/filesNick Allen
08/04/2021, 5:06 AMcoroutineContext[Job]!!.invokeOnCompletion { process.destroy()}
pgreze
08/04/2021, 7:29 AMdestroy
unless necessary, but not sure what’s the best practice regarding this function…