問題描述
我遇到了一個問題.有時,當我的 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");
這篇關于如何使用 Java 獲取 chromedriver 進程 PID?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!