最近我的项目要我在WebService里用Java调用Linux下的Shell 脚本,在网上找了一些资料,以供学习。
地址:http://brian.pontarelli.com/2005/11/11/java-runtime-exec-can-hang/
November 11, 2005 on 4:40 pm | In Java |
The next version of Savant is going to focus heavily on the stand-alone runtime and support for dialects and plugins. Supporting all that is largely handled by using a simple executor framework I wrote around Java 1.4 and lower’s Runtime.exec method. A few things to keep in mind when using this:
可以看出:
于是将waitFor()方法放在读取数据流后调用,目前没有发现什么问题。
后面的build中在waitFor()之前读取了数据流,bat文件就可以完整执行了:
Process proc = Runtime.getRuntime().exec(cmd); StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error"); StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output"); errorGobbler.start(); outputGobbler.start(); proc.waitFor(); class StreamGobbler extends Thread { InputStream is; String type; StreamGobbler(InputStream is, String type) { this.is = is; this.type = type; } public void run() { try { InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { if (type.equals("Error")) LogManager.logError(line); else LogManager.logDebug(line); } } catch (IOException ioe) { ioe.printStackTrace(); } } }
2. 另外一个需要注意的地方是:
如果调用的脚本中存在像sudo这样的需要tty的命令时,使用
String []cmdArray = new String[]{ "/bin/sh", "-c", "yourscriptname"};
这样的调用方式,会为脚本执行创建出一个tty环境,否则,运行过程会提示"sorry, you must have a tty to run xxx"的错误。
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, and even deadlock.
在exec()后 立即调用waitFor()会导致进程挂起。
3.当调用的外部命令中包含重定向(<、>),管道( | ) 命令时,exec(String command)的版本不能正确解析重定向、管道操作符。所以需要使用exec(String [] cmdArray)。
如, echo "hello world" > /home/admin/newFile.txt
ls -e | grep java
需要使用如下的调用方式
String []cmdArray = new String[]{ "/bin/sh", "-c", "ls -e | grep java"};
Runtime.getRuntime().exec(cmdArray);
地址:http://blog.csdn.net/moreorless/archive/2009/05/14/4182883.aspx