![](/img/trans.png)
[英]Java :Kill process runned by Runtime.getRuntime().exec()
[英]Kill Java Process after Completing Runtime.getRuntime().exec() method
我正在使用Runtime.getRuntime().exec()
在linux
环境中执行shell
脚本,但我看到 java 进程在完成此任务后没有终止。 完成此任务后如何停止/终止java 进程。
爪哇
private class Task implements Runnable{
@Override
public void run() {
try {
Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
}
} catch (IOException e) {
};
}
你有几个选择。 您可以使用Process#waitFor
阻塞直到任务完成
class Task implements Runnable{
@Override
public void run() {
try {
final Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
process.waitFor();
} catch (final IOException | InterruptedException e) {
// handle the error
}
};
}
如果您认为程序可能挂起,您可以将waitFor
包装在一个Thread
并join
超时。 超时后,您可以对进程调用destroy
。
class Task implements Runnable{
@Override
public void run() {
try {
final Process process = Runtime.getRuntime().exec(new String[]{shellfile}, null, new File(shellfilepath));
final Thread thread = new Thread(process::waitFor);
thread.start();
thread.join(1000);
process.destroy();
} catch (final IOException | InterruptedException e) {
// handle the error
}
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.