Chris Haines
Chris Haines

Reputation: 6535

Is it possible to end a process nicely in a Java application?

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?

Upvotes: 8

Views: 8153

Answers (5)

Tony Tonev
Tony Tonev

Reputation: 99

Using JNA's jna.jar and process.jar (from http://jna.java.net/) you send a WM_CLOSE message as follows:

int WM_CLOSE = 0x10;

HWND hwnd = User32.INSTANCE.FindWindow(null, windowTitle);
User32.INSTANCE.PostMessage(hwnd, WM_CLOSE, new WinDef.WPARAM(), new WinDef.LPARAM());

Upvotes: 3

Zarkonnen
Zarkonnen

Reputation: 22478

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.

Upvotes: 3

Matthew Murdoch
Matthew Murdoch

Reputation: 31453

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.

Upvotes: 2

Reginaldo
Reginaldo

Reputation: 907

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();

Upvotes: 1

dfa
dfa

Reputation: 116314

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

Upvotes: 3

Related Questions