Como encontrar e eliminar Win-Processes em execução no Java?
Pergunta
Preciso de uma maneira Java de encontrar um processo Win em execução do qual eu saiba o nome do executável.Quero verificar se ele está em execução agora e preciso de uma maneira de encerrar o processo, caso o encontre.
Solução
Você pode usar linha de comando ferramentas do Windows tasklist
e taskkill
e chamá-los a partir de Java usando Runtime.exec()
.
Outras dicas
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);
}
Exemplo:
public static void main(String args[]) throws Exception {
String processName = "WINWORD.EXE";
//System.out.print(isProcessRunning(processName));
if (isProcessRunning(processName)) {
killProcess(processName);
}
}
Há um pouco API fornecer a funcionalidade desejada:
https://github.com/kohsuke/winp
Biblioteca de Processo do Windows
Você pode usar uma ferramenta de linha de comando para matar processos como SysInternals PsKill e SysInternals PsList .
Você também pode usar o build-in tasklist.exe e taskkill.exe, mas aqueles só estão disponíveis no Windows XP Professional e mais tarde (não no Home Edition).
Use java.lang.Runtime.exec para executar o programa.
Aqui está uma maneira groovy de fazê-lo:
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}")
}
Use a seguinte classe para matar um processo do Windows ( se estiver em execução ). Eu estou usando o /F
linha de argumento de comando força para se certificar de que o processo especificado pelo argumento /IM
será encerrado.
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();
}
}
Você terá que chamar algum código nativo, já que IMHO não há nenhuma biblioteca que faz isso. Desde JNI é complicado e difícil que você pode tentar usar JNA (Java Native Access). https://jna.dev.java.net/
pequena mudança na resposta escrita pela Super Kakes
private static final String KILL = "taskkill /IMF ";
alterado para ..
private static final String KILL = "taskkill /IM ";
trabalho /IMF
opção doesnot .it não mata opção /IM
notepad..while realmente funciona