Skip to content

Instantly share code, notes, and snippets.

@dcsobral
Created February 1, 2012 18:25
Show Gist options
  • Save dcsobral/1718470 to your computer and use it in GitHub Desktop.
Save dcsobral/1718470 to your computer and use it in GitHub Desktop.
Process Traversable
import scala.sys.process._
import scala.util.control.ControlThrowable
class ProcTrav(pb: ProcessBuilder) extends Traversable[String] {
var iterating: Boolean = _
var exception: Option[Throwable] = _
// This is required to stop the process, but since we are not doing that...
// var process: Process = _ // Need to synchronize access to this
def logger[U](f: String => U): String => Unit = (input: String) => if (iterating) try { f(input) } catch {
case ex: ControlThrowable => iterating = false
exception = Some(ex)
// but how to stop the Process?
case other => throw other
}
def foreach[U](f: String => U) {
iterating = true
exception = None
// We need this to stop the process, but since we are not doing that...
// process = pb run ProcessLogger(logger(f))
// process.exitValue()
pb ! ProcessLogger(logger(f))
exception foreach (throw _)
}
}
object ProcTrav {
def apply(pb: ProcessBuilder) = new ProcTrav(pb)
}
@dcsobral
Copy link
Author

dcsobral commented Feb 1, 2012

Not thread-safe! I'm in no mood in making it thread-safe either. I'd like to stop the process that is executing, but I'm not sure that's possible at all. It seems there's no way other than passing a ProcessIO to run, which makes things suddenly much more complex. Doing that I can catch & handle IOException while reading from the stream, but I'm still getting NPE from... somewhere.

I could also put the whole run on a single thread, and try that, but, then, I don't have any way on logger to self-destroy.

So, at this point, I'm open for suggestions. I really need to stop the running process.

@dcsobral
Copy link
Author

dcsobral commented Feb 2, 2012

On SBT I could use runBuffered, which gets me the Process and calls buffer on ProcessLogger to wrap the execution. Perhaps this could make my job easier? I'll try that on trunk.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment