Commons-exec: freezes when I call executor.execute (commandLine);

I have no idea why this is hanging. I am trying to grab the output from a process launched via commons-exec and I keep hanging. I presented an example program demonstrating this behavior below.

import java.io.DataInputStream; import java.io.IOException; import java.io.PipedInputStream; import java.io.PipedOutputStream; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteException; import org.apache.commons.exec.PumpStreamHandler; public class test { public static void main(String[] args) { String command = "java"; PipedOutputStream output = new PipedOutputStream(); PumpStreamHandler psh = new PumpStreamHandler(output); CommandLine cl = CommandLine.parse(command); DefaultExecutor exec = new DefaultExecutor(); DataInputStream is = null; try { is = new DataInputStream(new PipedInputStream(output)); exec.setStreamHandler(psh); exec.execute(cl); } catch (ExecuteException ex) { } catch (IOException ex) { } System.out.println("huh?"); } } 
+3
source share
2 answers

According to javadoc , execute(CommandLine command) is synchronous, execute(CommandLine command, ExecuteResultHandler handler) , on the other hand, is asynchronous.

+9
source

The java command you select outputs the output to standard output. Your streaming should be uploaded to the input stream by your caller. This does not happen in your program.

You have to read the input stream ( is in your code) in a separate stream, because this is how streams work with streams. Note that you must start the read stream before calling execute() .

See also Capturing large volumes of output from Apache Commons-Exec

According to your other question, streaming output with commons-exec? you expect big data, so you should use streams with channels and you cannot use a simpler approach to using ByteArrayInputStream as output. The answer you give yourself suffers from the same problem as your code here.

+5
source

Source: https://habr.com/ru/post/1307838/


All Articles