开发者

Start shell script in background from java program

开发者 https://www.devze.com 2023-04-04 17:14 出处:网络
I currently start a shell script from my开发者_Go百科 Java by code looking like this: ProcessBuilder processBuilder = new ProcessBuilder();

I currently start a shell script from my开发者_Go百科 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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号