views:

741

answers:

2

I've created an Ant task to compile VB6 applications.

After some preprocessing of the source files, I start VB6.exe with the appropriate parameters using

Process p = Runtime.getRuntime().exec(...);
p.waitFor();

But when I press Ctrl+C while Ant is running, the script and my task are terminated but the spawned process is still running.

How can I automatically terminate the process I started when the Ant script gets terminated? What exactly happens if I press Ctrl+C? Is my task killed immediately or is there some way to react?

+1  A: 

Runtime.exec() runs the command in a separate OS process. When you press Ctrl+C you kill the Java process.

You can try Runtime.addShutdownHook(Thread hook). This hook thread will be called when the JVM is shutting down when you press Ctrl+C. Implement the hook thread which will try to kill the process which you started. To kill the process you need to find out the command on that OS and use that in the Runtime.exec().

Bhushan
using Runtime.exec() with kill or other OS specific command is ugly; Process#destroy() is better
dfa
+1  A: 

You may be interested in this code:

    final Process process = new ProcessBuilder("blah blah").start();
    Runtime.getRuntime().addShutdownHook(new Thread() {

        @Override
        public void run() {
            process.destroy();
        }

    });
    process.waitFor();

javadoc for addShutdownHook:

The Java virtual machine shuts down in response to two kinds of events:

  • The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or
  • The virtual machine is terminated in response to a user interrupt, such as typing ^C,
    or a system-wide event, such as user logoff or system shutdown.
dfa