Skip to content

Instantly share code, notes, and snippets.

@tbje
Last active Sep 26, 2017
Embed
What would you like to do?
Running a shell command in scala native capturing output
import scalanative.native._, stdlib._, stdio._
@extern
object Pipe {
def popen(cmd: CString, mode: CString): Ptr[FILE] = extern
def pclose(file: Ptr[FILE]): Unit = extern
}
object Shell {
def runCommand(cmd: String, cwd: Option[String] = None): Option[String] =
Zone { implicit z =>
val buffSize = 100
val buff = alloc[CChar](buffSize)
val s = new StringBuilder()
val fullCmd = cwd.map(dir => s"cd $dir && ").getOrElse("") + cmd
Pipe.popen(toCString(fullCmd), toCString("r")) match {
case null =>
None
case filePtr =>
while (fgets(buff, buffSize, filePtr) != null) {
s.++=(fromCString(buff))
}
Pipe.pclose(filePtr)
Some(s.result())
}
}
}
object HelloShell extends App {
import Shell._
println(runCommand("ls -l").getOrElse(""))
println("-" * 50)
println(runCommand("ls -l", Some("/")).getOrElse(""))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment