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();
            }

        }
    }
}

使用示例:

public class Example {

    public static void main(String[] args) {

        String prefix = "chrom"; //模糊匹配谷歌进程
        SingleProcess.comfirmSingleProcess(prefix);
    }
}

猜你喜欢

转载自blog.csdn.net/javabuilt/article/details/79927339
今日推荐