0

I'm trying to execute a script via JAVA code, but it's not being executed. I tried execute() of Process class but later switched to ProcessBuilder after some searching hoping to make this work. But the script's not getting executed.

JAVA Code:

String fileName = "pkgdiff.sh";
File file = new File(fileName);
ProcessBuilder builder = new ProcessBuilder("/bin/sh", fileName);
builder.directory(file.getParentFile());
Process process = builder.start();
process.waitFor();
StringBuffer output = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";                       
while ((line = reader.readLine())!= null) {
    output.append(line + "\n");
}
LOGGER.info("### Script Execution result --> " + fileName+"-->" + output);

Script file:

#!/bin/sh
.. rest of the content
Magesh Kumaar
  • 1,485
  • 2
  • 10
  • 29

1 Answers1

1

How much output is the script producing? You should be processing its output before you call waitFor(), otherwise the process might block if it fills up its output buffer.

From the Java API:

Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • It's exactly 30 lines and each line would take about 1-2 seconds to print – Magesh Kumaar Jan 24 '17 at 13:57
  • So where am I supposed to put the `waitFor()`? before the logger print? – Magesh Kumaar Jan 24 '17 at 13:58
  • Yes, before the log message. Or after, since you're not checking the exit code. The main thing not to call it until `reader.readLine()` returns null. – John Kugelman Jan 24 '17 at 14:00
  • Thanks and I've added the same. Still nothing. I've no clue what I'm missing. Since if I replace /bin/sh with echo it's working fine :/ – Magesh Kumaar Jan 24 '17 at 14:01
  • @MageshKumaar Regardless of how much output a process might produce, `waitFor` will *wait for the process to finish,* so you should never call that method until you are done interacting with the process. – VGR Jan 24 '17 at 15:14