java 调用batch处理_Java调用外部shell/batch command/程序: Runtime.getRuntime().exec()

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:

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.

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()方法之前读取数据流

永远要先从标准错误流中读取,然后再读取标准输出流

那就首先说点Runtime类吧,他是一个与JVM运行时环境有关的类,这个类是Singleton的。我说几个自己觉得重要的地方。

1、Runtime.getRuntime()可以取得当前JVM的运行时环境,这也是在Java中唯一一个得到运行时环境的方法。

2、Runtime上其他大部分的方法都是实例方法,也就是说每次进行运行时调用时都要用到getRuntime方法。

3、Runtime中的exit方法是退出当前JVM的方法,估计也是唯一的一个吧,因为我看到System类中的exit实际上也是通过调用Runtime.exit()来退出JVM的,这里说明一下Java对Runtime返回值的一般规则(后边也提到了),0代表正常退出,非0代表异常中止,这只是Java的规则,在各个操作系统中总会发生一些小的混淆。

4、Runtime.addShutdownHook()方法可以注册一个hook在JVM执行shutdown的过程中,方法的参数只要是一个初始化过但是没有执行的Thread实例就可以。(注意,Java中的Thread都是执行过了就不值钱的哦)

5、说到addShutdownHook这个方法就要说一下JVM运行环境是在什么情况下shutdown或者abort的。文档上是这样写的,当最后一个非精灵进程退出或者收到了一个用户中断信号、用户登出、系统shutdown、Runtime的exit方法被调用时JVM会启动shutdown的过程,在这个过程开始后,他会并行启动所有登记的shutdown

hook(注意是并行启动,这就需要线程安全和防止死锁)。当shutdown过程启动后,只有通过调用halt方法才能中止shutdown的过程并退出JVM。

那什么时候JVM会abort退出那?首先说明一下,abort退出时JVM就是停止运行但并不一定进行shutdown。这只有JVM在遇到SIGKILL信号或者windows中止进程的信号、本地方法发生类似于访问非法地址一类的内部错误时会出现。这种情况下并不能保证shutdown

hook是否被执行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值