Ho bisogno di un modo Java per trovare un processo Win in esecuzione da cui conosco il nome dell'eseguibile. Voglio vedere se è in esecuzione in questo momento e ho bisogno di un modo per uccidere il processo se l'ho trovato.
Puoi usare gli strumenti di Windows a riga di comando tasklist
e taskkill
e chiamarli da Java usando Runtime.exec()
.
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);
}
ESEMPIO:
public static void main(String args[]) throws Exception {
String processName = "WINWORD.EXE";
//System.out.print(isProcessRunning(processName));
if (isProcessRunning(processName)) {
killProcess(processName);
}
}
C'è una piccola API che fornisce la funzionalità desiderata:
https://github.com/kohsuke/winp
Libreria processi di Windows
Potresti usare uno strumento da riga di comando per uccidere processi come SysInternals PsKill e SysInternals PsList .
È anche possibile utilizzare il tasklist.exe incorporato e taskkill.exe, ma questi sono disponibili solo su Windows XP Professional e versioni successive (non in Home Edition).
Utilizzare Java.lang.Runtime.exec per eseguire il programma.
Ecco un modo fantastico di farlo:
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}")
}
Utilizzare la seguente classe per kill un processo di Windows ( se è in esecuzione ). Sto usando l'argomento della riga di comando force /F
per assicurarmi che il processo specificato dall'argomento /IM
venga terminato.
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();
}
}
piccolo cambio di risposta scritto da Super kakes
private static final String KILL = "taskkill /IMF ";
Cambiato in ..
private static final String KILL = "taskkill /IM ";
l'opzione /IMF
non funziona. Non uccide il blocco note ... mentre l'opzione /IM
funziona davvero
Dovrai chiamare un codice nativo, poiché IMHO non ha alcuna libreria che lo faccia. Poiché JNI è ingombrante e difficile, potresti provare a utilizzare JNA (Java Native Access). https://jna.dev.Java.net/