3

I currently start a shell script from my Java by code looking like this:

ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.directory("/directory/where/the/script/is/located/");
String[] command = new String[]{"sh", "myScript.sh"};
processBuilder.command(command);
Map<String, String> env = processBuilder.environment();
//tweak the environment with needed additions
env.put(...);
Process p = processBuilder.start();

stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

// read the output from the command
String line;
while ((line = stdInput.readLine()) != null)
{
  logger.fine(line);
}
p.waitFor();
int returnCode = p.exitValue();
// Return something according to the return code
return ...;

If I now want to start the script and not wait for it to end (and thus losing the ability to return according to return code), but still with being able to tweak the environment beforehand? how should I proceed?

Thank you

2
  • Not waiting for it to end also means that you lose ability to get the output from the process, right? Commented Sep 13, 2011 at 10:02
  • @Nivas not if it is started in a different thread, then both stdout and stderr from the process can (and must) be captured Commented Sep 13, 2011 at 10:20

1 Answer 1

5

Just do the entire thing in a new thread.

Wrap the entire above code in a Runnable and start a Thread for it. Your main code can continue doing something else. In the runnable once you get the result from the child process use some notify(or observer pattern) to notify interested parties.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.