原理:获取系统所有进程列表,遍历,然后进行模糊匹配,将匹配到的进程杀死!
作用:保证在系统中只有一个程序进程实例。
/*** 确保系统中只有一个程序实例* 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())));// 创建集合 存放 进程+pidList<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();}}}
}
使用示例:
public class Example {public static void main(String[] args) {String prefix = "chrom"; //模糊匹配谷歌进程SingleProcess.comfirmSingleProcess(prefix);}
}
-----------------------Linux-----------------------
1.首先通过
Process pid=Runtime.getRuntime().exec("ps -ef");
找出linux当前运行的所有进程。
2.再把pid写入流中:
BufferedReader br = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
3.读取流中的指定信息:
String line = null;while ((line = br.readLine()) != null) {if(line.contains("进程名")){logger.info("进程分流信息是:"+line);String [] inf=line.split(" +");for(int j=0;j<inf.length;j++){logger.info("inf["+j+"]="+inf[j]);}logger.info("进程号信息是:"+inf[1]);Process pi=Runtime.getRuntime().exec("kill -9 "+inf[1]);logger.info("已执行杀进程");}else{// logger.info(""+line);}}
4.这样就把指定的进程给kill成功了!
注:logger.info()是为了打印日志的,可以替换成System.out.println();