27

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.

Tomasz Nurkiewicz
  • 311,858
  • 65
  • 665
  • 652
GHad
  • 9,505
  • 6
  • 32
  • 40

8 Answers8

45
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);
 }
}
1-14x0r
  • 1,598
  • 1
  • 14
  • 18
  • 3
    If taskkill does not end your process, you might want to add the "/F" parameter to force it. – Max Hohenegger Jul 21 '14 at 15:08
  • good looks! Didn't know that was a valid option here. I updated the answer. Thanx – 1-14x0r Feb 04 '15 at 19:10
  • minus 1 because the taskkill command has invalid syntax. It should be `"taskkill /F /IM "` – BullyWiiPlaza Jun 15 '15 at 11:12
  • @KaraRawson: No, it's not working that way. Neither on the command line nor in Java. – BullyWiiPlaza Jun 19 '15 at 16:11
  • 1
    @BullyWiiPlaza i apologize, you are correct. I tried this on my workstation and it doesn't work now. Maybe a windows update or something changed. I did post this over 4 years ago. The only reason i say this is that it was working in a production environment.. However that's server 2008. Anyways i edited the post for you. Good find, thanx – 1-14x0r Jul 01 '15 at 21:25
16

You can use command line windows tools tasklist and taskkill and call them from Java using Runtime.exec().

Tomasz Nurkiewicz
  • 311,858
  • 65
  • 665
  • 652
3

There is a little API providing the desired functionality:

https://github.com/kohsuke/winp

Windows Process Library

Nikita Koksharov
  • 8,672
  • 52
  • 63
3

Here's a groovy way of doing it:

final Process jpsProcess = "cmd /c jps".execute()
final BufferedReader reader = new BufferedReader(new InputStreamReader(jpsProcess.getInputStream()));
def jarFileName = "FileName.jar"
def processId = null
reader.eachLine {
    if (it.contains(jarFileName)) {
        def args = it.split(" ")
        if (processId != null) {
            throw new IllegalStateException("Multiple processes found executing ${jarFileName} ids: ${processId} and ${args[0]}")
        } else {
            processId = args[0]
        }
    }
}
if (processId != null) {
    def killCommand = "cmd /c TASKKILL /F /PID ${processId}"
    def killProcess = killCommand.execute()
    def stdout = new StringBuilder()
    def stderr = new StringBuilder()
    killProcess.consumeProcessOutput(stdout, stderr)
    println(killCommand)
    def errorOutput = stderr.toString()
    if (!errorOutput.empty) {
        println(errorOutput)
    }
    def stdOutput = stdout.toString()
    if (!stdOutput.empty) {
        println(stdOutput)
    }
    killProcess.waitFor()
} else {
    System.err.println("Could not find process for jar ${jarFileName}")
}
Craig
  • 1,882
  • 3
  • 17
  • 35
2

You could use a command line tool for killing processes like SysInternals PsKill and SysInternals PsList.

You could also use the build-in tasklist.exe and taskkill.exe, but those are only available on Windows XP Professional and later (not in the Home Edition).

Use java.lang.Runtime.exec to execute the program.

arturh
  • 5,837
  • 4
  • 36
  • 46
1

Use the following class to kill a Windows process (if it is running). I'm using the force command line argument /F to make sure that the process specified by the /IM argument will be terminated.

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class WindowsProcess
{
    private String processName;

    public WindowsProcess(String processName)
    {
        this.processName = processName;
    }

    public void kill() throws Exception
    {
        if (isRunning())
        {
            getRuntime().exec("taskkill /F /IM " + processName);
        }
    }

    private boolean isRunning() throws Exception
    {
        Process listTasksProcess = getRuntime().exec("tasklist");
        BufferedReader tasksListReader = new BufferedReader(
                new InputStreamReader(listTasksProcess.getInputStream()));

        String tasksLine;

        while ((tasksLine = tasksListReader.readLine()) != null)
        {
            if (tasksLine.contains(processName))
            {
                return true;
            }
        }

        return false;
    }

    private Runtime getRuntime()
    {
        return Runtime.getRuntime();
    }
}
BullyWiiPlaza
  • 12,477
  • 7
  • 82
  • 129
0

small change in answer written by Super kakes

private static final String KILL = "taskkill /IMF ";

Changed to ..

private static final String KILL = "taskkill /IM ";

/IMF option doesnot work .it does not kill notepad..while /IM option actually works

Nomesh DeSilva
  • 1,613
  • 3
  • 22
  • 40
Harvendra
  • 1
  • 1
0

You will have to call some native code, since IMHO there is no library that does it. Since JNI is cumbersome and hard you might try to use JNA (Java Native Access). https://jna.dev.java.net/

jb.
  • 20,419
  • 16
  • 91
  • 130