在groovy中执行许多子进程失败

2024-05-16 14:17:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要创建一个调用应用程序(c++二进制)4000次的脚本。应用程序接受一些参数,并为每个调用将一个zip文件写入磁盘。因此,当脚本执行时,4000个zip文件将被写入磁盘。应用程序支持多个线程。在

我首先创建了一个bash脚本来完成这项工作,并且运行良好。但现在我需要脚本独立于平台。因此,我尝试将脚本移植到groovy,如下所示:

for (int i = 1; i <= 4000; i++) {
  def command = """myExecutable
                 a=$argA
                 b=$outDir"""

  def proc = command.execute()                 // Call *execute* on the string
  proc.waitFor()                               // Wait for the command to finish
  // Obtain status and output
  println "return code: ${ proc.exitValue()}"
  println "stderr: ${proc.err.text}"
  println "stdout: ${proc.in.text}" // *out* from the external program is *in* for groovy

  println "iteration : " + i

}

但在381个zipfiles被写入磁盘后,脚本就挂起了。我是否需要在每次呼叫或类似事件后关闭流程?在

这里: http://groovy.codehaus.org/Process+Management

它说它知道java.lang.Process可能挂起或死锁。在groovy中不能做这样的事情吗?在

我还将在python中的try中给出它,看看它是否会产生相同的问题


Tags: 文件thetextin脚本应用程序forexecute
2条回答

可能是输出流阻塞:

(1..<4000).each { i ->
    println "iteration : $i"

    def command = """myExecutable
                 a=$argA
                 b=$outDir"""

    def proc = command.execute()
    // Consume the outputs from the process and pipe them to our output streams
    proc.consumeProcessOutput( System.out, System.err )

    // Wait for the command to finish
    proc.waitFor()

    // Obtain status
    println "return code: ${proc.exitValue()}"
}

是的,您应该关闭属于进程的流。在

或者,如@tim_yates所说,您应该使用consumerprocessoutput,或者在concurrent解决方案中,waitForProcessOutput,这将为您关闭它们。在

对于并行计算,可以使用smth。像这样:

import groovyx.gpars.GParsPool

GParsPool.withPool(8){ // Start in pool with 8 threads.
  (1..4000).toList().eachParallel {
    def p = "myExecutable a=$argA b=$outDir".execute()
    def sout = new StringBuffer();
    def serr = new StringBuffer();
    p.waitForProcessOutput(sout, serr)
    synchronized (System.out) {
      println "return code: ${ p.exitValue()}"
      println "stderr: $serr"
      println "stdout: $sout"
      println "iteration $it"
    }
  }
}

相关问题 更多 >