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

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

I've faced a problem. Sometimes, while my JUnit tests are running, command webDriver.quit(); isn't killing chromedriver process so the next test can't start. In that case I want to add some method which may kill process manually on Linux, but I can't figure out how to get PID of chromedriver so I can do something like: Runtime.getRuntime().exec(KILL + PID);

推荐答案

你可以使用 pgrep 找到 PID,然后杀死它:

You can find PIDs using pgrep and then kill it:

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

<小时>

更新

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

Another and more simple solution seems to be

    Runtime.getRuntime().exec("pkill chromedriver");

相关文章