I need a Java way to find a running Win process from which I know to name of the executable. I want to look whether it is running right now and I need a way to kill the process if I found it.
If you want to kill all java.exe processes : taskkill /F /IM java.exe /T .
If you start the process from with in your Java application (ex. by calling Runtime. exec() or ProcessBuilder. start() ) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.
If you want to check the work of java application, run 'ps' command with '-ef' options, that will show you not only the command, time and PID of all the running processes, but also the full listing, which contains necessary information about the file that is being executed and program parameters.
private static final String TASKLIST = "tasklist"; private static final String KILL = "taskkill /F /IM "; public static boolean isProcessRunning(String serviceName) throws Exception { Process p = Runtime.getRuntime().exec(TASKLIST); BufferedReader reader = new BufferedReader(new InputStreamReader( p.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); if (line.contains(serviceName)) { return true; } } return false; } public static void killProcess(String serviceName) throws Exception { Runtime.getRuntime().exec(KILL + serviceName); }
EXAMPLE:
public static void main(String args[]) throws Exception { String processName = "WINWORD.EXE"; //System.out.print(isProcessRunning(processName)); if (isProcessRunning(processName)) { killProcess(processName); } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With