我试图从命令行运行一个程序,如果通过程序传递的图像文件损坏和/或命名错误,它将无限期地运行。我可以测试以确保文件名是有效的,但是如果rootkit损坏了图像,这对我没有帮助。我的理解是退出程序的唯一方法是创建一个单独的线程,但sys.process.!!
阻塞直到执行完成。
val imageInfo: Option[String] = Some(s"python vol.py -f $memFile imageinfo".!!.trim)
答案 0 :(得分:1)
在完成之前,您不必让import scala.sys.process.{Process, ProcessLogger}
var (iiOut, iiErr) = ("", "") // for collecting Process output
val getii = Process(s"python vol.py -f $memFile imageinfo")
.run(ProcessLogger(iiOut += _, iiErr += _))
// . . .
// do other useful stuff
// or set a timeout alarm and wait for it
// . . .
val imageInfo: Option[String] =
if (getii.isAlive()) {
// report failure
getii.destroy()
None
} else if (getii.exitValue() != 0 || iiErr != "") {
// report failure
None
} else
Some(iiOut.trim)
阻止。
def date = new Date()
def day = date[Calendar.DAY_OF_MONTH]
答案 1 :(得分:0)
您可以Future
与Await
一起使用来衡量太长的流程,例如:
import scala.concurrent.ExecutionContext.Implicits.global
val sb = new StringBuffer // sb for capture output
val io = BasicIO(false, sb, None)// Creates a `ProcessIO` that appends its output to a `StringBuffer`
val p = s"python vol.py -f $memFile imageinfo".run()
val f = Future {
p.exitValue() //Blocks until this process exits and returns the exit code.
Some(sb.toString)// return the process result
}
try {
val str: Option[String] = Await.result(f, Duration.apply(1, TimeUnit.SECONDS))
} catch {
case e: TimeoutException => {
println("run too long")
p.destroy() //destroy this process when too long
}
}