Last active
September 26, 2017 07:56
-
-
Save tbje/235a4fa8b5ec094699251dea2c98c38a to your computer and use it in GitHub Desktop.
Running a shell command in scala native capturing output
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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