小编典典

如何使用Java获取chromedriver进程PID?

linux

我遇到了一个问题。有时,当我的JUnit测试正在运行时,请命令webDriver.quit();。不会杀死chromedriver进程,因此下一个测试无法开始。在那种情况下,我想添加一些可以在Linux上手动终止进程的方法,但是我不知道如何获取chromedriver的PID,因此可以执行以下操作:Runtime.getRuntime()。exec(KILL
+ PID);


阅读 897

收藏
2020-06-07

共1个答案

小编典典

您可以使用pgrep找到PID,然后将其杀死:

    private void killChromedriver() throws IOException, InterruptedException {
        String command = "pgrep chromedriver";
        Process process = Runtime.getRuntime().exec(command);
        BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
        List<String> processIds = getProcessedIds (process, br);
        for (String pid: processIds) {
                Process p = Runtime.getRuntime().exec("kill -9 " + pid);
                p.waitFor();
                p.destroy();
        }
    }
    private List<String> getProcessedIds(Process process, BufferedReader br) throws IOException, InterruptedException {
        process.waitFor();

        List<String> result = new ArrayList<>();
        String processId ;

        while (null != (processId = br.readLine())) {
            result.add(processId);
        }

        process.destroy();
        return result;
    }

更新

另一个更简单的解决方案似乎是

    Runtime.getRuntime().exec("pkill chromedriver");
2020-06-07