I want to kill the particular Java process in Window with the following command line:
taskkill /f /pid <my_pid>
I didn't find a way to get the pid of my process on windows without using JNA api. I found several answers that use JNA but I'm looking for a simpler solution.
Following is the Java code that I used (which does not work):
Field f = p.getClass().getDeclaredField("handle");
f.setAccessible(true);
long handle = f.getLong(p);
System.out.println("Kill pid " + handle);
Finally I found a solution.
I have used wmic process get commandline, processid
windows command to get the PID.
Following is my Killer.java :
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
public class Killer {
public static void main(String[] args) throws Exception {
ArrayList<String> cmds = new ArrayList<String>();
cmds.add("wmic");
cmds.add("process");
cmds.add("get");
cmds.add("commandline,processid");
ProcessBuilder pb = new ProcessBuilder(cmds);
Process p = pb.start();
//p.waitFor();
BufferedReader rd = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
int pid=0;
while((line = rd.readLine()) != null)
{
if(line.contains(args[0]) && !line.contains("Killer"))
{
System.out.println("OK" + line);
String[] split = line.split(" ");
pid=Integer.parseInt(split[split.length - 1]);
}
else
{
//System.out.println(" " + line);
}
}
cmds = new ArrayList<String>();
System.out.println("Kill pid " + pid);
cmds.add("taskkill");
cmds.add("/T");
cmds.add("/F");
cmds.add("/PID");
cmds.add("" + pid);
pb = new ProcessBuilder(cmds);
pb.start();
}
}
Hope it will help you.