近我的项目要我在WebService里用Java调用Linux下的Shell 脚本,在网上找了一些资料,以供学习。

地址:http://brian.pontarelli.com/2005/11/11/java-runtime-exec-can-hang/

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:

  1. Always read from the streams prior to calling waitFor. Otherwise you could end up waiting forever on Windows and other OS platforms whose I/O buffers can’t store enough from standard out and standard error to ensure the program has finished. These platforms will pause the execution of whatever is running until something reads the buffered content from standard out and standard error. I would imagine all platforms suffer from this, but some platforms have larger buffers than others. Needless to say, always read from the streams first.
  2. Always read from standard error first. I ran across a bug where some OS platforms will always open standard out, but never close it. What this means is that if you read from standard out first and the process only writes to standard error, you’ll hang forever waiting to read. If you read from standard error first, you’ll always be okay on these platforms because the OS seems to shutdown standard error. I think however, that the best way to handle all cases is to check both standard error and standard out for readiness and only read from them if they have something to offer. The downside I could see here is that error isn’t ready, but eventually will be.

可以看出:

  • 永远要在调用waitFor()方法之前读取数据流
  • 永远要先从标准错误流中读取,然后再读取标准输出流

于是将waitFor()方法放在读取数据流后调用,目前没有发现什么问题。

后面的build中在waitFor()之前读取了数据流,bat文件就可以完整执行了:

[java] view plaincopy
  1. Process proc = Runtime.getRuntime().exec(cmd);
  2. StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "Error");
  3. StreamGobbler outputGobbler = new StreamGobbler(proc.getInputStream(), "Output");
  4. errorGobbler.start();
  5. outputGobbler.start();
  6. proc.waitFor();
  7. class StreamGobbler extends Thread {
  8. InputStream is;
  9. String type;
  10. StreamGobbler(InputStream is, String type) {
  11. this.is = is;
  12. this.type = type;
  13. }
  14. public void run() {
  15. try {
  16. InputStreamReader isr = new InputStreamReader(is);
  17. BufferedReader br = new BufferedReader(isr);
  18. String line = null;
  19. while ((line = br.readLine()) != null) {
  20. if (type.equals("Error"))
  21. LogManager.logError(line);
  22. else
  23. LogManager.logDebug(line);
  24. }
  25. } catch (IOException ioe) {
  26. ioe.printStackTrace();
  27. }
  28. }
  29. }

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);

JAVA shell grep相关推荐

  1. java shell_jshell – Java Shell

    java shell Earlier we looked into Java REPL i.e. jshell basics. Today we will learn some more featur ...

  2. Shell -----grep

    简介 grep (global search regular expression(RE) and print out the line,全面搜索正则表达式并把行打印出来)是一种强大的文本搜索工具,它 ...

  3. java shell spool_批量快速的导入导出Oracle的数据(spool缓冲池、java实现)

    1. Java代码实现思路 BufferedWriter writefile = new BufferedWriter(new FileWriter(file)); writefile.write(& ...

  4. linux shell grep 搜索数据 赋值变量 没有换行符

    问题: 用grep写shell的时候,发现一个很奇怪的问题,当我用命令grep搜索数据时,返回的多行数据时是按每行显示的,但是当我在shell里把这个搜索命令赋值到变量后,输出这个变量,就变成一行输出 ...

  5. shell grep 变量_Shell应用:巧用xargs 轻松实现上万文件的筛选压缩

    背景 Linux 下某个目录下有小文件好几万个,命名规则按日期每小时 N 个,想要过滤出指定日期的文件并添加到压缩文件中,记录下脚本化的过程如下. 正则过滤存在的问题 首先,直接进入该目录,由于文件数 ...

  6. shell grep 变量_老司机给出的关于 shell 脚本的8个建议,必收!

    这八个建议,来源于键者几年来编写 shell 脚本的一些经验和教训.事实上开始写的时候还不止这几条,后来思索再三,去掉几条无关痛痒的,最后剩下八条.毫不夸张地说,每条都是精挑细选的,虽然有几点算是老生 ...

  7. Shell—grep、sed、awk

    Shell学习 Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁.Shell 既是一种命令语言,又是一种程序设计语言. Shell 是指一种应用程序,这个应用程序提供了一个界 ...

  8. JAVA shell export_Java 远程调用Shell

    Java 远程调用Shell 上一篇 / 下一篇  2014-01-21 13:29:22 / 个人分类:Java Remote Shell Scripts need to export the EN ...

  9. java shell排序_八大排序算法——希尔(shell)排序

    一.动图演示 二.思路分析希尔排序是把记录按下标的一定增量分组,对每组使用直接插入排序算法排序:随着增量逐渐减少,每组包含的关键词越来越多,当增量减至1时,整个文件恰被分成一组,算法便终止. 简单插入 ...

最新文章

  1. 【笔记】mysql入门语句8条
  2. Hibernate 缓存机制
  3. Leetcode 134. 加油站 解题思路及C++实现
  4. 深入理解内存(3):内存交换技术,虚拟内存
  5. 搞笑之----普通话
  6. Android Json操作
  7. it跟java的区别_详细介绍JAVA和C++区别
  8. Linux 免密登录和配置环境变量
  9. Perl 安装Inline 和 Inline Java模组(windows)
  10. 浅析智能访客机的应用
  11. 面试|详细分析ScheduledThreadPoolExecutor(周期性线程池)的原理
  12. Matlab二值图像栅格化和圆域范围框定
  13. mongoDB Ops Manager
  14. python tableview没有数据时的占位处理_iOS造轮子系列-TableView空数据显示占位图片 runtime实现...
  15. 【深度解刨C语言】符号篇(全)
  16. ctf_show_misc_wp
  17. 二维和三维CAD设计Autodesk AutoCAD 2021
  18. VR家居为什么盛行?可以解决哪些传统家居的痛点?
  19. Twitter技术主管回怼马斯克:不懂技术乱评价!马斯克:He’s fired
  20. 10道集合框架面试题(含解析),来看看你会多少

热门文章

  1. 【正一专栏】梅西、内马尔分开明天会更好
  2. 读张鸣-《辛亥:摇晃的中国》感
  3. php 间隔时间执行任务,PHP间隔一段时间执行代码的方法
  4. API接口调用里的QPS指什么?百度语音API里的QPS实例说明
  5. Spring Boot使用缓存功能
  6. IMXRT1052/1064 如何将代码存放在ITCM中
  7. 声明和定义结构体需要注意的问题
  8. 【HDU2683 TCE-frep number system 完全数+二项展开式】
  9. 合并a[0..mid]和a[mid+1,n-1],其中这两个数组分别有序
  10. 二值化函数Threshold