问题描述
我遇到了一个问题。有时,在我的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;
}
UPDATE
另一个更简单的解决方案似乎是
Another and more simple solution seems to be
Runtime.getRuntime().exec("pkill chromedriver");
这篇关于如何使用Java获得chromedriver进程PID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!