tags:

views:

447

answers:

4

In a Java application:

currentProcess = Runtime.getRuntime().exec("MyWindowsApp.exe");
...
currentProcess.destroy();

Calling destroy simply kills the process and doesn't allow any user cleanup or exit code to run. Is it possible to send a process a WM_CLOSE message or similar?

+1  A: 

You could use Process.getOutputStream to send a message to the stdin of your app, eg:

PrintStream ps = new PrintStream(currentProcess.getOutputStream());
ps.println("please_shutdown");
ps.close();

Of course this means you have to contrive to listen on stdin in the Windows app.

Zarkonnen
Thanks, of all the solutions, this one seems the best!
Hainesy
+1  A: 

you can try with JNA, importing user32.dll and defining an interface that defines at least CloseWindow

dfa
+1 JNI maybe? I wonder if there's a utility like 'kill -SIGTERM' in Windows
ATorras
+1  A: 

A dirty solution would be making your MyWindowsApp register its identifier somewhere like file and create another windows app that sends WM_CLOSE (let's name it MyWindowsAppCloser) to another applications.

With this in hand, you would code the following using 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();

Reginaldo
+1  A: 

Not without resorting to native code. Process.destroy() causes a forced termination. On Windows this is equivalent to calling TerminateProcess(). On Unix it is equivalent to a SIGQUIT and causes the application to core dump.

Matthew Murdoch
SIGKILL doesn't dump core! It's not SIGQUIT (which does dump core by default).
Chris Jester-Young
I stand corrected. I guess Unix versions of Java must send a SIGQUIT (core dumps definitely occur). I'll update this answer. Thank you.
Matthew Murdoch