Skip to content

Instantly share code, notes, and snippets.

@tbje
Last active September 26, 2017 07:56
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 tbje/235a4fa8b5ec094699251dea2c98c38a to your computer and use it in GitHub Desktop.
Save tbje/235a4fa8b5ec094699251dea2c98c38a to your computer and use it in GitHub Desktop.
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