I am looking for a Java tool/package/library that will allow me to force-kill
a child process.
This tool/package/library must work on Windows platform (mandatory).
Support for Linux/Unix is desired.
My Problem
My Java code creates a child process that will simply not react to the
standard Java way for killing a child process: process.destroy(), and,
since I do not have the child's source code, I cannot program it to
better handle termination requests.
I have tried closing the child process' error input and output stream
before calling destroy(), and for no effect.
I have even tried passing ctrlBreak signal (char=3) directly into
child.getOutputStream(), and again have received the same results.
The workaround I have finally managed to find was to:
-
Obtain the child's PID upon its creation
This can be done in Windows by diffing the process lists
before and after the child's creation (getRuntime().exec("tasklist /v")
) -
Use the child's PID to issue a force kill system command
in Windows:getRuntime().exec("taskkill /pid " + childPid + " /f")
But – this is complex code I have no desire to debug and maintain, plus the problem
itself, I have no doubt, was previously encountered by many other java developers,
which leads me to the hope that such a Java tool/package/library already exists.
I just don't know its name…
PS: My child process was created by Runtime.getRuntime().exec(cmd)
, but
I get the same behaviour using a ProcessBuilder.
Best Answer
There is a leaner way to do this using Java JNA.
This works definitely for Windows and Linux, i assume that you can do the same for other platforms too.
The biggest problem of Java process handling is the lack of a method to get the process id of the process started with untime.getRuntime().exec().
Assuming you got the pid of a process, you always can start a kill -9 command in linux, or use similar ways to kill a process in windows.
Here is a way to get the process id natively for linux (borrowed from the selenium framework, :) ), and with the help of JNA this also can be done for windows (using native Windows API calls).
For this to work (for Windows) you first have to get the JNA Library at JAVA NATIVE ACCESS (JNA): Downloads or get it from maven
Look at the following code, which will get the pid of a (in this example windows) program (most of the code is actually debris to get a working java program going):
Hope this helps, ;)...