Here’s the translation of the Go code to Kotlin, with explanations in Markdown format suitable for Hugo:
In the previous example, we looked at spawning external processes. We do this when we need an external process accessible to a running Kotlin process. Sometimes we just want to completely replace the current Kotlin process with another (perhaps non-Kotlin) one. To do this we’ll use Kotlin’s implementation of the classic exec function.
When we run our program it is replaced by ls.
Note that Kotlin doesn’t offer a classic Unix fork function. Usually this isn’t an issue though, since starting coroutines, spawning processes, and exec’ing processes covers most use cases for fork.
In Kotlin, we use ProcessBuilder to create and start new processes. The inheritIO() method is used to redirect the subprocess’s standard I/O to the current process. We use waitFor() to wait for the process to complete and get its exit code.
Remember that this approach doesn’t exactly replicate the behavior of syscall.Exec in Go, which replaces the current process. In Kotlin, we’re creating a new process and waiting for it to finish.