34
src/nativeMain/kotlin/com/infendro/shell/Shell.native.kt
Normal file
34
src/nativeMain/kotlin/com/infendro/shell/Shell.native.kt
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.infendro.shell
|
||||
|
||||
import kotlinx.cinterop.CPointer
|
||||
import kotlinx.cinterop.ExperimentalForeignApi
|
||||
import kotlinx.cinterop.refTo
|
||||
import kotlinx.cinterop.toKString
|
||||
import platform.posix.*
|
||||
|
||||
@ExperimentalForeignApi
|
||||
internal actual suspend fun execute(
|
||||
command: Array<String>,
|
||||
directory: String?,
|
||||
): Shell.Result {
|
||||
val command = command.joinToString(" ") { "\"$it\"" }
|
||||
if (directory != null) {
|
||||
chdir(directory)
|
||||
}
|
||||
val stream = popen(command, "r")!!
|
||||
val value = stream.readLines().joinToString("")
|
||||
val code = pclose(stream)
|
||||
return Shell.Result(code, value)
|
||||
}
|
||||
|
||||
@ExperimentalForeignApi
|
||||
private fun CPointer<FILE>.readLines(): List<String> {
|
||||
val lines = mutableListOf<String>()
|
||||
val buffer = ByteArray(4096)
|
||||
while (true) {
|
||||
val line = fgets(buffer.refTo(0), buffer.size, this)
|
||||
if (line == null) break
|
||||
lines.add(line.toKString())
|
||||
}
|
||||
return lines
|
||||
}
|
||||
Reference in New Issue
Block a user