示例示例Java判断进程是否存在的方法有很多,以使用Runtime类的exec()方法来实现为例:通过Runtime类的()方法获取Runtime实例对象:
Java判断进程是否存在的方法有很多,以使用Runtime类的exec()方法来实现为例:
1. 首先,通过Runtime类的getRuntime()方法获取Runtime实例对象:
Runtime runtime = Runtime.getRuntime();
2. 然后,使用exec()方法执行一个操作系统命令,来检测指定的进程是否存在:
Process process = runtime.exec("tasklist /fi \"imagename eq "+processName+"\"");
3. 最后,使用process.waitFor()方法来等待进程执行完毕,并使用process.exitValue()方法来获取进程结束时的返回值:
int exitValue = process.waitFor();
如果返回值为0,则表示指定的进程存在;如果返回值不为0,则表示指定的进程不存在。
是一个完整的代码示例:
public static boolean isProcessExist(String processName) {
boolean isExist = false;
try {
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("tasklist /fi \"imagename eq "+processName+"\"");
int exitValue = process.waitFor();
if (exitValue == 0) {
isExist = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return isExist;
}
本站系公益性非盈利分享网址,本文来自用户投稿,不代表边看边学立场,如若转载,请注明出处
评论列表(9条)