在Java應用程序:是否有可能在Java應用程序中很好地結束進程?
currentProcess = Runtime.getRuntime().exec("MyWindowsApp.exe");
...
currentProcess.destroy();
調用destroy
簡單地殺死進程,不允許任何用戶的清理或退出代碼運行。是否可以發送一個進程WM_CLOSE
消息或類似的消息?
在Java應用程序:是否有可能在Java應用程序中很好地結束進程?
currentProcess = Runtime.getRuntime().exec("MyWindowsApp.exe");
...
currentProcess.destroy();
調用destroy
簡單地殺死進程,不允許任何用戶的清理或退出代碼運行。是否可以發送一個進程WM_CLOSE
消息或類似的消息?
你可以使用Process.getOutputStream將消息發送到您的應用程序的標準輸入,如:
PrintStream ps = new PrintStream(currentProcess.getOutputStream());
ps.println("please_shutdown");
ps.close();
當然,這意味着你必須圖謀聽取有關Windows應用程序標準輸入。
你可以嘗試JNA,進口user32.dll中並定義至少定義CloseWindow
+1 JNI也許吧?我想知道在Windows中是否有像'kill -SIGTERM'這樣的工具 – ATorras 2009-06-05 12:52:21
一個骯髒的解決辦法是讓你的MyWindowsApp註冊的標識,如文件的地方,並創建另一個窗口的應用程序發送WM_CLOSE(界面讓我們把它命名爲MyWindowsAppCloser)到另一個應用程序。
掌握了這些,你會編寫以下使用Java 1.6
currentProcess = Runtime.getRuntime().exec("MyWindowsApp.exe"); ... // get idMyWindowsApp where MyWindowsApp stored its identifier killerProcess = new ProcessBuilder("MyWindowsAppCloser.exe", idMyWindowsApp).start(); killerProcess.waitFor(); int status = currentProcess.waitFor();
不是沒有訴諸本地代碼。 Process.destroy()
導致強制終止。在Windows上,這相當於撥打TerminateProcess()
。在Unix上它相當於一個SIGQUIT
並導致應用程序進行核心轉儲。
SIGKILL不會轉儲核心!它不是SIGQUIT(默認情況下會轉儲核心)。 – 2009-06-05 12:15:22
使用JNA的jna.jar和process.jar(從http://jna.java.net/)您發送WM_CLOSE消息如下:
int WM_CLOSE = 0x10;
HWND hwnd = User32.INSTANCE.FindWindow(null, windowTitle);
User32.INSTANCE.PostMessage(hwnd, WM_CLOSE, new WinDef.WPARAM(), new WinDef.LPARAM());
感謝,所有的解決方案,這一次似乎是最好的! – 2009-06-05 13:25:48