java.lang.Process.exitValue()和waitFor()和destroy()

本文详细介绍了Java中通过exec方法启动子进程后的三种主要控制方式:destroy、exitValue及waitFor方法。destroy方法用于强制终止子进程;exitValue方法获取子进程的退出状态码,但需确保子进程已结束;waitFor方法则使主线程等待直至子进程完成执行,并返回退出状态码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

currProcess=currRuntime.exec(cmd);
这个返回一个process对象
destroy,exitValue,waitFor
有三个方法



看官方文档

waitFor
public abstract int waitFor()
                     throws InterruptedException
Causes the current thread to wait, if necessary, until the process represented by this Process object has terminated. This method returns immediately if the subprocess has already terminated. If the subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits.
Returns:
the exit value of the subprocess represented by this Process object. By convention, the value 0 indicates normal termination.
Throws:
InterruptedException - if the current thread is interrupted by another thread while it is waiting, then the wait is ended and an InterruptedException is thrown.
一直挂起,直到子进程执行结束
返回值0表示正常退出




exitValue
public abstract int exitValue()
Returns the exit value for the subprocess.
Returns:
the exit value of the subprocess represented by this Process object. By convention, the value 0 indicates normal termination.
Throws:
IllegalThreadStateException - if the subprocess represented by this Process object has not yet terminated
返回0是正常
但是如果子进程还没结束
会报异常



destroy
public abstract void destroy()
Kills the subprocess. The subprocess represented by this Process object is forcibly terminated.
强制关掉子进程


总体来说
还是调用    waitfor()==0
进行判断
既可以让子进程跑完
还可以判断子进程的执行状态
最佳的选择就是使用这个!  waitfor()  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值