摘要:本文主要向大家介绍了JAVA语言之Java如何获取系统进程,并杀死指定进程?通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
本文主要向大家介绍了JAVA语言之Java如何获取系统进程,并杀死指定进程?通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助。
原理:获取系统所有进程列表,遍历,然后进行模糊匹配,将匹配到的进程杀死!
作用:保证在系统中只有一个程序进程实例。
/**
* 确保系统中只有一个程序实例
* 1.如果客户端启动前,操作系统中有残留进程,则杀死进程,然后启动
* 2.如果客户端启动前,操作系统中没有残留进程,则直接启动
* 时间:2018-04-13
* @author Jason
*
*/
public class SingleProcess {
public static Logger logger = Logger.getLogger(SingleProcess.class);
/**
* 确认进程,获取进程,杀死进程
* @param prefix 进程名前缀
*/
public static void comfirmSingleProcess(String prefix) {
if(prefix == null) {
throw new NullPointerException("The prefix is null,please check it!!");
}
// 声明文件读取流
BufferedReader out = null;
BufferedReader br = null;
try {
// 创建系统进程
ProcessBuilder pb = new ProcessBuilder("tasklist");
Process p = pb.start();
// 读取进程信息
out = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getInputStream()), Charset.forName("GB2312")));
br = new BufferedReader(new InputStreamReader(new BufferedInputStream(p.getErrorStream())));
// 创建集合 存放 进程+pid
List<string> list = new ArrayList<>();
// 读取
String ostr;
while ((ostr = out.readLine()) != null){
// 将读取的进程信息存入集合
list.add(ostr);
}
// 遍历所有进程
for (int i = 3; i < list.size(); i++) {
// 必须写死,截取长度,因为是固定的
String process = list.get(i).substring(0, 25).trim(); // 进程名
String pid = list.get(i).substring(25, 35).trim(); // 进程号
// 匹配指定的进程名,若匹配到,则立即杀死
if(process.startsWith(prefix)){
Runtime.getRuntime().exec("taskkill /F /PID "+pid);
}
}
// 若有错误信息 即打印日志
String estr = br.readLine();
if (estr != null) {
logger.error(estr);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关流
try {
if(out != null) { out.close(); }
} catch (IOException e) {
e.printStackTrace();
}
try {
if(br != null) { br.close(); }
} catch (IOException e) {
e.printStackTrace();
}
}
}
}</string>
使用示例:
public class Example {
public static void main(String[] args) {
String prefix = "chrom"; //模糊匹配谷歌进程
SingleProcess.comfirmSingleProcess(prefix);
}
}
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注编程语言JAVA频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号