Come trovare e uccidere l'esecuzione di Vincere-dall'interno i Processi di Java?
Domanda
Ho bisogno di un Java modo per trovare una esecuzione di Vincere il processo, da cui non so il nome del file eseguibile.Voglio vedere se è in esecuzione in questo momento e ho bisogno di un modo per uccidere il processo se l'ho trovato.
Soluzione
È possibile utilizzare la riga di comando strumenti di windows tasklist
e taskkill
e li chiamano da Java utilizzando Runtime.exec()
.
Altri suggerimenti
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'è un po ' di API che fornisce la funzionalità desiderata:
https://github.com/kohsuke/winp
Windows Process Library
Si potrebbe utilizzare una riga di comando strumento per uccidere i processi come SysInternals PsKill e SysInternals PsList.
Si potrebbe anche usare il build-in tasklist.exe e taskkill.exe ma quelli sono disponibile solo in Windows XP e versioni successive (non nella Home Edition).
Utilizzare java.lang.Runtime.exec per eseguire il programma.
Ecco una groovy modo per 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 il seguente classe uccidere un processo di Windows (se è in esecuzione).Io sto usando la forza argomento della riga di comando /F
per assicurarsi che il processo specificato dal /IM
l'argomento sarà 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();
}
}
Si dovrà chiamare alcuni di codice nativo, dato che IMHO non c'è nessuna libreria che fa.Dal JNI è ingombrante e difficile, si può provare a utilizzare JNA (Java Native Access). https://jna.dev.java.net/
piccola variazione nella risposta scritto da Super kakes
private static final String KILL = "taskkill /IMF ";
Cambiato ..
private static final String KILL = "taskkill /IM ";
/IMF
opzione doesnot lavoro .non uccidere il blocco note..mentre /IM
opzione funziona davvero