How does the “scala.sys.process” from Scala 2.9 work?

I just had a look at the new scala.sys and scala.sys.process packages to see if there is something helpful here. However, I am at a complete loss.

Has anybody got an example on how to actually start a process?

And, which is most interesting for me: Can you detach processes?

A detached process will continue to run when the parent process ends and is one of the weak spots of Ant.

UPDATE:

There seem to be some confusion what detach is. Have a real live example from my current project. Once with z-Shell and once with TakeCommand:

Z-Shell:

if ! ztcp localhost 5554; then
    echo "[ZSH] Start emulator"
    emulator                        \
    -avd    Nexus-One               \
    -no-boot-anim                   \
    1>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.out   \
    2>~/Library/Logs/${PROJECT_NAME}-${0:t:r}.err   &
    disown
else
    ztcp -c "${REPLY}"
fi;

Take-Command:

IFF %@Connect[localhost 5554] lt 0 THEN
   ECHO [TCC] Start emulator
   DETACH emulator -avd Nexus-One -no-boot-anim
ENDIFF

In both cases it is fire and forget, the emulator is started and will continue to run even after the script has ended. Of course having to write the scripts twice is a waste. So I look into Scala now for unified process handling without cygwin or xml syntax.


First import:

import scala.sys.process.Process

then create a ProcessBuilder

val pb = Process("""ipconfig.exe""")

Then you have two options:

  1. run and block until the process exits

    val exitCode = pb.!
    
  2. run the process in background (detached) and get a Process instance

    val p = pb.run
    

    Then you can get the exitcode from the process with (If the process is still running it blocks until it exits)

    val exitCode = p.exitValue
    

If you want to handle the input and output of the process you can use ProcessIO:

import scala.sys.process.ProcessIO
val pio = new ProcessIO(_ => (),
                        stdout => scala.io.Source.fromInputStream(stdout)
                          .getLines.foreach(println),
                        _ => ())
pb.run(pio)

I'm pretty sure detached processes work just fine, considering that you have to explicitly wait for it to exit, and you need to use threads to babysit the stdout and stderr. This is pretty basic, but it's what I've been using:

/** Run a command, collecting the stdout, stderr and exit status */
def run(in: String): (List[String], List[String], Int) = {
  val qb = Process(in)
  var out = List[String]()
  var err = List[String]()

  val exit = qb ! ProcessLogger((s) => out ::= s, (s) => err ::= s)

  (out.reverse, err.reverse, exit)
}