On Windows to gracefully stop a java application in a standard way you need to send Ctrl + C to it. This only works with console apps, but Eclipse uses javaw.exe
instead of java.exe
. To solve this open the launch configuration, JRE tab and select "Alternative JRE:". The "Java executable" group box appears and allows to enter the alternate executable "java".
Now we need an external program to send Ctrl-C to a process with a hidden console. I found hints here and here. Our program attaches to the console of the desired process and sends the console event.
#include <stdio.h>
#include <windows.h>
int main(int argc, char* argv[])
{
if (argc == 2) {
unsigned pid = 0;
if (sscanf_s(argv[1], "%u", &pid) == 1) {
FreeConsole();
if (AttachConsole(pid)) {
SetConsoleCtrlHandler(NULL, TRUE);
GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0);
return 0;
}
}
}
return 1;
}
Test java program:
public class Shuthook {
public static void main(final String[] args) throws Exception {
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.out.println("Shutting down...");
}
});
String sPid = ManagementFactory.getRuntimeMXBean().getName();
sPid = sPid.substring(0, sPid.indexOf('@'));
System.out.println("pid: " + sPid);
System.out.println("Sleeping...");
Thread.sleep(1000000);
}
}
Terminating it:
C:\>killsoft.exe 10520
Test program output in Eclipse:
pid: 10520
Sleeping...
Shutting down...