简体   繁体   English

从java程序后台启动shell脚本

[英]Start shell script in background from java program

I currently start a shell script from my Java by code looking like this: 我目前通过代码从我的Java启动一个shell脚本,如下所示:

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. 将上述代码包装在Runnable中并为其启动一个Thread。 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. 在runnable中,一旦从子进程获得结果,就使用一些notify(或者观察者模式)来通知感兴趣的各方。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM