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 
7
  • What do you expect the code to do and what does it actually? Commented Jan 24, 2017 at 13:34
  • I'm trying to execute a script via JAVA code and it's not getting executed. Commented Jan 24, 2017 at 13:36
  • Do the user that executes the java process has security permissions to do so? Does the script have permission to be executed? Commented Jan 24, 2017 at 13:46
  • @JorgeCampos yes I have the permission. I can execute it fine via the terminal Commented Jan 24, 2017 at 13:48
  • If i replace /bin/sh with echo it's working fine Commented Jan 24, 2017 at 13:53

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

It's exactly 30 lines and each line would take about 1-2 seconds to print
So where am I supposed to put the waitFor()? before the logger print?
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.
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 :/
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.