I'm using Apache Commons Exec and trying to start subprocess that would work for the entire duration of application. It should start process, accepttwo input commands and just stay in background. Now its only accepts one command (at least what stdout shows) and terminates. Can you aid me?
CommandLine cmdLine = new CommandLine("app.exe");
cmdLine.addArgument("argument");
DefaultExecutor executor = new DefaultExecutor();
OutputStream os = new ByteArrayOutputStream();
InputStream is = new ByteArrayInputStream(("command1;\ncommand2;\n").getBytes());
executor.setStreamHandler(new PumpStreamHandler(os,null,is));
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
executor.execute(cmdLine,resultHandler);
System.out.println(os.toString());
resultHandler.waitFor();
I think these two lines are in the wrong order:
System.out.println(os.toString());
resultHandler.waitFor();
Should be like this (to allow the process to complete it's output):
resultHandler.waitFor();
System.out.println(os.toString());
EDIT
Still not 100% sure what you are after, but think I missed the "just stay in background" part of your original request. One way to achieve this would be to use a PipedInputStream
& PipedOutputStream
pair to talk to the process. When you are done, you can close the output stream. If you wanted access to the output from the process before it finishes, you could use a similar technique for the output with the direction reversed.
I don't have a windows machine handy, but the following works for me:
public static void main(String[] args) {
try {
CommandLine cmdLine = new CommandLine("/bin/bash");
DefaultExecutor executor = new DefaultExecutor();
OutputStream os = new ByteArrayOutputStream();
PipedOutputStream pos = new PipedOutputStream();
PipedInputStream pis = new PipedInputStream(pos);
executor.setStreamHandler(new PumpStreamHandler(os, null, pis));
DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();
executor.execute(cmdLine, resultHandler);
PrintWriter pw = new PrintWriter(pos);
pw.println("ls -l /usr");
pw.println("pwd");
pw.close();
resultHandler.waitFor();
System.out.println(os.toString());
} catch (Exception e) {
e.printStackTrace();
}
}