[英]Wait until process exit that run by Runtime.exec(“wmic process call create notepad.exe”)
我正在開發一個能夠運行程序的應用程序,可以監視它們以在用戶意外關閉它們並在注銷時關閉程序的情況下重新打開。
我可以通過解析wmic process call create <program>
的輸入流來獲取程序的進程ID。
我使用此代碼段運行程序並檢測用戶何時關閉程序。 我的問題是我使用( wmic
)運行程序的命令在運行它們后立即退出。
如何實現程序退出檢測?
我的代碼:
public static void main(String[] args) {
Process process = null;
try {
process = Runtime.getRuntime()
.exec("wmic process call create \"notepad.exe\"");
BufferedReader stdin = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String processIdLine = "";
String line;
while ((line = stdin.readLine()) != null) {
if (line.contains("ProcessId")) {
processIdLine = line;
break;
}
System.out.println(line);
}
stdin.close();
String[] param = processIdLine.split("=");
if (param.length > 1) {
String pId = param[1];
pId = pId.replaceAll(";", " ");
pId = pId.replaceAll(" ", "");
System.out.println("ID : " + pId);
}
try {
process.waitFor();
// I want it to hang here till notepad closed.
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("PROCESSE EXIT");
} catch (IOException e) {
e.printStackTrace();
}
}
注意:我不想使用tasklist命令並比較進程是否已退出
請查看ZeroTurnaround的ZT-exec庫,它為您提供了很多現成的功能:
try {
new ProcessExecutor().command("java", "-version").exitValues(3).execute();
} catch (InvalidExitValueException e) {
System.out.println("Process exited with " + e.getExitValue());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.