Created
February 1, 2012 18:25
-
-
Save dcsobral/1718470 to your computer and use it in GitHub Desktop.
Process Traversable
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 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) | |
} |
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
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
torun
, which makes things suddenly much more complex. Doing that I can catch & handleIOException
while reading from the stream, but I'm still gettingNPE
from... somewhere.I could also put the whole
run
on a single thread, andtry
that, but, then, I don't have any way onlogger
to self-destroy.So, at this point, I'm open for suggestions. I really need to stop the running process.