Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using scala.sys.process with timeout

I find it extreemly cool to use standard syntax like

import scala.sys.process._
    val countLogger = ProcessLogger(line => {println ("out line: " + line)},
                                 line => {println ("err line: " + line)})

    val exitCode = ("cat prog.c" #&& "gcc prog.c -o prog -lm" 
            #&& "echo running, this may hang" #&& "prog.exe") ! countLogger

    println("exitCode = " + exitCode)

It however happens that last process hangs. Is it possible to kill it on timeout?

like image 416
Val Avatar asked Mar 15 '15 22:03

Val


1 Answers

You can wrap your process in a Future(blocking(_)) and if it doesn't return after the time-out, you call process.destroy().

That's what I have done for my small Processor library, e.g. see here. Instead of using ! to eagerly wait for the exit-code, you use the run method. Here is an adaption from the README:

import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.sys.process._

val p = "sleep 100".run()               // start asynchronously
val f = Future(blocking(p.exitValue())) // wrap in Future
val res = try {
  Await.result(f, duration.Duration(2, "sec"))
} catch {
  case _: TimeoutException => 
    println("TIMEOUT!")
    p.destroy()
    p.exitValue()
}
like image 189
0__ Avatar answered Oct 05 '22 19:10

0__