Pregunta

Necesito una forma Java de encontrar un proceso Win en ejecución del cual sepa el nombre del ejecutable.Quiero ver si se está ejecutando en este momento y necesito una forma de finalizar el proceso si lo encuentro.

¿Fue útil?

Solución

Puede utilizar herramientas de Windows de línea de comando tasklist y taskkill y llamarlos desde Java usando Runtime.exec().

Otros consejos

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);

 }

EJEMPLO:

public static void main(String args[]) throws Exception {
 String processName = "WINWORD.EXE";

 //System.out.print(isProcessRunning(processName));

 if (isProcessRunning(processName)) {

  killProcess(processName);
 }
}

Hay una pequeña API que proporciona la funcionalidad deseada:

https://github.com/kohsuke/winp

Biblioteca de procesos de Windows

Podrías usar una herramienta de línea de comando para matar procesos como SysInternals PsKill y Lista de Ps de SysInternals.

También puede utilizar tasklist.exe y taskkill.exe integrados, pero solo están disponibles en Windows XP Professional y versiones posteriores (no en Home Edition).

Usar java.lang.Runtime.exec para ejecutar el programa.

Aquí tienes una forma genial de hacerlo:

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}")
}

Utilice la siguiente clase para matar un proceso de Windows (si esta corriendo).Estoy usando el argumento de línea de comando forzar /F para asegurarse de que el proceso especificado por el /IM La discusión terminará.

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();
    }
}

Tendrás que llamar a algún código nativo, ya que en mi humilde opinión no existe ninguna biblioteca que lo haga.Dado que JNI es engorroso y difícil, puede intentar utilizar JNA (Java Native Access). https://jna.dev.java.net/

pequeño cambio en la respuesta escrita por Super kakes

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

Cambiado a ..

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

/IMF La opción no funciona. No mata el bloc de notas... mientras /IM La opción realmente funciona.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top