[Question] Handle user input to interactive commands
dinuta opened this issue · comments
Hi team,
I have the following piece of code which seems to work on Windows, but not on Linux.
private static void sendStdInputToProcess(ProcessState processState, String stdInput) throws IOException {
OutputStream stdin = processState.getStartedProcess().getProcess().getOutputStream();
InputStream stdout = processState.getStartedProcess().getProcess().getInputStream();
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(stdin));
//reader = new BufferedReader(new InputStreamReader(stdout));
writer.write(stdInput);
writer.flush();
Scanner scanner = new Scanner(stdout); //<- reader
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
writer.close();
}
}
Inputs & Outputs:
Win: cmd.exe /c "set /P id=Enter id: " stdInput= "something\n". Result: PASS
Linux: "/bin/sh -c ssh-keygen" or any command that needs interactive input. stdInput= "some\some\n". Result: FAIL because it hangs forever
Do you see anything what I miss here ?
Are you adding a line break to the end of your input?
Maybe add writer.newLine()
after writer.write(stdInput)
?
Thank you, one more question please.
I use the following when starting the process
StartedProcess startedProcess = new ProcessExecutor()
.command(command)
.environment(environment.getEnvAndVirtualEnv())
.destroyOnExit()
.readOutput(true)
.redirectError(outputStream)
.redirectInput(System.in)
.start();
I wonder if .redirectInput(System.in) is fine from your point of view, because for any interactive and non-interactive command I obtain an Interrupted exception:
11:13:57.034 [ForkJoinPool.commonPool-worker-3] DEBUG org.zeroturnaround.exec.ProcessExecutor - Executing [/bin/sh, -c, read A] with environment {SWAPPED_ENV}.
11:13:57.042 [ForkJoinPool.commonPool-worker-3] DEBUG org.zeroturnaround.exec.ProcessExecutor - Started Process[pid=4378, exitValue="not exited"]
11:13:57.869 [main] INFO com.axway.b2bi.automation.signitrack.agent.utils.ProcessStateUtils - Sent stdIn user string 'y'
11:13:57.869 [main] INFO com.axway.b2bi.automation.signitrack.agent.utils.ProcessStateUtils - Sent enter KEY
11:13:57.869 [main] INFO com.axway.b2bi.automation.signitrack.agent.utils.ProcessStateUtils - Sent enter KEY
11:13:57.870 [WaitForProcess-Process[pid=4378, exitValue="not exited"]] DEBUG org.zeroturnaround.exec.WaitForProcess - Process[pid=4378, exitValue=0] stopped with exit code 0
11:13:57.880 [Thread-0] ERROR org.zeroturnaround.exec.stream.InputStreamPumper - Got exception while reading/writing the stream
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at org.zeroturnaround.exec.stream.InputStreamPumper.run(InputStreamPumper.java:89)
at java.base/java.lang.Thread.run(Thread.java:829)