使用 Kotlin/Native,如何执行外部操作系统可执行文件或 $PATH 命令并与其 stdin、stdout 和 stderr 流交互?

Les*_*ood 5 kotlin kotlin-native

我正在研究用 Kotlin/Native 编写的命令行工具的概念证明,因为它似乎是跨平台二进制文件的理想语言和运行时。

该命令行工具需要定期与 os 用户 $PATH 或 shell 环境中的操作系统可执行文件、命令和/或 shell 函数进行交互。但是,我在kotlin-native 示例或文档中没有看到任何可能指示如何执行以下操作的示例:

  • 执行操作系统可执行文件或 $PATH 命令
  • 获取执行的返回码(整数)
  • 确保执行进程的 stdin、stdout 和 stderr 文件描述符流可以分别表示为 OutputStream 和 InputStreams

在 JVM 领域,我们可以使用java.lang.ProcessBuilder所有这些,但这显然在 Kotlin/Native 中不可用。

我找到了 cinterop/posixplatform.posix.system函数,但这并不能让您访问进程的流。

在我的网络研究中,我发现了一个非常好的 C教程,它表明唯一干净的方法是使用forkanddup2等,但我不清楚这是否或如何转换为 Kotlin/Native 代码。

Dir*_*ann 2

我用 kotlin Native 做了一些尝试,并成功为 jvm、mac、unix 和(未经测试的)windows 执行了 posix exec 命令...

https://github.com/hoffipublic/minimal_kotlin_multiplatform

目标共同点

fun String.executeCommand(
    redirectStderr: Boolean = true
): String? = MppProcess.executeCommand(this, redirectStderr)

interface IMppProcess {
    fun executeCommand(
        command: String,
        redirectStderr: Boolean = true
    ): String?
}

expect object MppProcess : IMppProcess {
    override fun executeCommand(
        command: String,
        redirectStderr: Boolean
    ): String?
}
Run Code Online (Sandbox Code Playgroud)

目标jvm

actual object MppProcess : IMppProcess {
    actual override fun executeCommand(
        command: String,
        redirectStderr: Boolean
    ): String? {
        return runCatching {
            ProcessBuilder(command.split(Regex("(?<!(\"|').{0,255}) | (?!.*\\1.*)")))
                //.directory(workingDir)
                .redirectOutput(ProcessBuilder.Redirect.PIPE)
                .apply { if (redirectStderr) this.redirectError(ProcessBuilder.Redirect.PIPE) }
                .start().apply { waitFor(60L, TimeUnit.SECONDS) }
                .inputStream.bufferedReader().readText()
        }.onFailure { it.printStackTrace() }.getOrNull()
    }
}
Run Code Online (Sandbox Code Playgroud)

目标 mac/unix/windows

import kotlinx.cinterop.refTo
import kotlinx.cinterop.toKString
import platform.posix.fgets
import platform.posix.pclose
import platform.posix.popen

actual object MppProcess : IMppProcess {
    actual override fun executeCommand(
        command: String,
        redirectStderr: Boolean
    ): String? {
        val commandToExecute = if (redirectStderr) "$command 2>&1" else command
        val fp = popen(commandToExecute, "r") ?: error("Failed to run command: $command")

        val stdout = buildString {
            val buffer = ByteArray(4096)
            while (true) {
                val input = fgets(buffer.refTo(0), buffer.size, fp) ?: break
                append(input.toKString())
            }
        }

        val status = pclose(fp)
        if (status != 0) {
            error("Command `$command` failed with status $status${if (redirectStderr) ": $stdout" else ""}")
        }

        return stdout
    }
}
Run Code Online (Sandbox Code Playgroud)

现在只执行了 ls ,但它有效。