Issue
I have a Windows .bat
file that starts a java program. For the sake of convenience I have created an Eclipse external tools configuration to start it directly from the IDE and to read its standard output from the Eclipse console.
However, when I terminate the process from Eclipse with the terminate button (the red square) in the Console view, the program is still running.
How to kill it from Eclipse (without creating a separate launch configuration that will search it and kill it programmatically)?
Solution
The best workaround I found so far is a reusable external applications launcher:
import java.lang.ProcessBuilder.Redirect;
public class Main {
public static void main(String[] args) throws Exception {
Process process = new ProcessBuilder(args[0])
.redirectOutput(Redirect.INHERIT)
.redirectError(Redirect.INHERIT)
.start();
Thread thread = new Thread(() -> readInput(args[1]));
thread.setDaemon(true);
thread.start();
process.waitFor();
}
private static void readInput(String commandLinePart) {
try {
while (System.in.read() != -1);
killProcess(commandLinePart);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void killProcess(String commandLinePart) throws Exception {
final String space = " ";
String[] commandLine = "wmic process where \"commandLine like '%placeholder%'\" delete"
.replaceAll("placeholder", commandLinePart).split(space);
new ProcessBuilder(commandLine).start();
}
}
The idea is to start this application instead of the external one and pass it the information about the target application as command line arguments.
The launcher application then starts the process, redirects the output and error streams (so that I see the target application output in the Eclipse console), waits until the target process is completed and waits for EOF from the standard input.
The last point actually does the trick: When I kill the process from the Eclipse console, the standard input reaches EOF, and the launcher application knows that it's time to stop the target process as well.
The Eclipse External Tools Configuration dialog looks now like this:
Location
is always the same for all configurations and points to the start.bat
file that simply runs the launcher application:
java -jar C:\ExternalProcessManager\ExternalProcessManager.jar %1 %2
It also takes the two command line arguments:
- The target process (in my case
test.bat
which simply starts my test application:java -jar Test.jar
). - The part of command line used to start the application (in my case
Test.jar
), so that launcher application can uniquely identify and kill the target process when I terminate the process from Eclipse console.
Answered By - Dragan Bozanovic