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

我遇到了一个问题。 有时,在我的JUnit测试运行时,命令webDriver.quit(); 是不是杀死chromedriver进程所以下一个测试无法启动。 在这种情况下,我想添加一些可能在Linux上手动杀死进程的方法,但我无法弄清楚如何获得chromedriver的PID,所以我可以做类似的事情:Runtime.getRuntime()。exec(KILL + PID);

你可以使用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 processIds = getProcessedIds (process, br); for (String pid: processIds) { Process p = Runtime.getRuntime().exec("kill -9 " + pid); p.waitFor(); p.destroy(); } } private List getProcessedIds(Process process, BufferedReader br) throws IOException, InterruptedException { process.waitFor(); List result = new ArrayList<>(); String processId ; while (null != (processId = br.readLine())) { result.add(processId); } process.destroy(); return result; } 

UPDATE

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

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