Groovy记录进程输出的方法

Dou*_*rel 6 io groovy multithreading asynchronous

我想在我的Grails应用程序中启动一个长时间运行的命令行进程,当它到达时将每行输出记录到控制台,并异步执行其他操作,同时进程和日志记录活动继续进行.(在某些时候,我想要对每行输出做一些其他事情,比如记录到文件或查找某些值并触发其他操作.但是为了这个问题的目的,登录到控制台是好的.)

下面是我提出的执行此操作的代码.它有效,但启动logger线程而没有明确地终止它让我感到困扰 - 它会正常终止吗?它会变成僵尸吗?我宁愿告诉Groovy将进程输出直接发送到System.out流 - 类似于command.execute(outputStream=System.out)- 但是没有找到一种非阻塞的方法来做到这一点.你能建议一个更好的方法吗?

def runCommand(command) {
    def process = command.execute()
    def out = process.getInputStream()
    def logger = Thread.start { out.eachLine { println it } }
    process.waitForOrKill(TIMEOUT_IN_MILLIS)
    return process // use to get exit code et cetera
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ell 11

查看ProcessGroovy文档,我看到有一个方法consumeProcessOutput(OutputStream输出,OutputStream错误).我试着用以下方式重写你的方法,希望它是非阻塞的:

def runCommand(command) {
  def process = command.execute()
  process.consumeProcessOutput(System.out, System.err)
  println 'requested consume output' //hoping this will come out first
  process.waitForOrKill(TIMEOUT_IN_MILLIS)
  return process // use to get exit code et cetera
}
Run Code Online (Sandbox Code Playgroud)

当我使用命令'dir'在Windows XP上运行它时,我得到以下输出:

requested consume output
file1    file2  ...
Run Code Online (Sandbox Code Playgroud)

成功!:)