Using a thread to capture process output

前端 未结 4 486
深忆病人
深忆病人 2020-12-06 22:11

I am using a thread to capture stream output from a process, and then outputting that stream to the eclipse console. The question I have is when to terminate the thread that

相关标签:
4条回答
  • 2020-12-06 22:43

    You need to process reading the output in a separate thread, theres an example here

    0 讨论(0)
  • 2020-12-06 22:50

    You will need to have two threads. One to handle the I/O and another to wait for process completion (Process.waitFor()) and set a flag telling the I/O thread to quit when it exhausts the data.

    0 讨论(0)
  • 2020-12-06 22:56

    You can use VerboseProcess from jcabi-log (I'm a developer):

    String name = new VerboseProcess(
      new ProcessBuilder("executable with output")
    ).stdout();
    

    The only dependency you need:

    <dependency>
      <groupId>com.jcabi</groupId>
      <artifactId>jcabi-log</artifactId>
      <version>0.7.5</version>
    </dependency>
    
    0 讨论(0)
  • 2020-12-06 22:58

    You need to use Process.waitFor() to wait for process completion.

    Additionally, you need to consume stdout and stderr concurrently in order to avoid blocking and a possible process hang. Consequently you need two threads to read these streams, and to continue reading whilst the streams are available.

    See this Javaworld article for more info and a StreamGobbler implementation to consume the stdout/err.

    0 讨论(0)
提交回复
热议问题