Skip to content

Instantly share code, notes, and snippets.

@andhikayuana
Forked from seanf/process.kt
Created July 10, 2023 03:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andhikayuana/4c47a4198270bb014334651ae0bd2cc5 to your computer and use it in GitHub Desktop.
Save andhikayuana/4c47a4198270bb014334651ae0bd2cc5 to your computer and use it in GitHub Desktop.
Execute process from Kotlin
import java.lang.ProcessBuilder.Redirect
import java.util.concurrent.TimeUnit
fun String.runCommand(workingDir: File? = null) {
val process = ProcessBuilder(*split(" ").toTypedArray())
.directory(workingDir)
.redirectOutput(Redirect.INHERIT)
.redirectError(Redirect.INHERIT)
.start()
if (!process.waitFor(10, TimeUnit.SECONDS)) {
process.destroy()
throw RuntimeException("execution timed out: $this")
}
if (process.exitValue() != 0) {
throw RuntimeException("execution failed with code ${process.exitValue()}: $this")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment