I need to run shell scripts or system commands using process builder. In some cases the command will ask for user input. For example, I have a java program "TestScanner" that takes an integer from command line and print it out. If I run it directly in terminal, something like
$bash -c "java TestScanner"
Enter a number:3
Number entered:3
$
The program displayed message for input. Then I input "3", then it printed out the result and the program terminated.
Now I need to run the command
bash -c "java TestScanner"
from a java process builder. Code is
// cmdList has 3 elements: bash, -c, java TestScanner
ProcessBuilder pb = new ProcessBuilder(cmdList);
pb.redirectErrorStream(true);
pb.directory(new File(workDir));
Process p = pb.start();
InputStream in = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = br.readLine()) != null)
{
System.out.println("Line: " + line);
}
When I run the above code snippet, it just hang there. I even could not see the message "Enter a number". I am not sure whether this is because p.getOutputStream() is waiting? How to detect that an input is requested by the program? I tried code snippet from here Java Process with Input/Output Stream and it does not work in my case. Thanks