如何从 Java 中查找和终止正在运行的 Win-Processes?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/81902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 08:05:05  来源:igfitidea点击:

How to find and kill running Win-Processes from within Java?

javawindowsprocess

提问by GHad

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.

我需要一种 Java 方法来查找正在运行的 Win 进程,从中我知道可执行文件的名称。我想看看它现在是否正在运行,如果找到它,我需要一种方法来终止该进程。

采纳答案by arturh

You can use command line windows tools tasklistand taskkilland call them from Java using Runtime.exec().

您可以使用命令行窗口工具tasklisttaskkill并使用Runtime.exec().

回答by jb.

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/

您将不得不调用一些本机代码,因为恕我直言,没有库可以做到这一点。由于 JNI 既麻烦又困难,您可能会尝试使用 JNA(Java Native Access)。https://jna.dev.java.net/

回答by arturh

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

您可以使用命令行工具来终止SysInternals PsKillSysInternals 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).

您也可以使用内置的 tasklist.exe 和 taskkill.exe,但这些仅适用于 Windows XP Professional 及更高版本(不适用于家庭版)。

Use java.lang.Runtime.execto execute the program.

使用java.lang.Runtime.exec执行程序。

回答by Daniel Lindner

There is a little API providing the desired functionality:

有一些 API 提供了所需的功能:

https://github.com/kohsuke/winp

https://github.com/kohsuke/winp

Windows Process Library

Windows 进程库

回答by 1-14x0r

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

回答by Craig

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

回答by Harvendra

small change in answer written by Super kakes

Super kakes 写的答案的小变化

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

Changed to ..

变成 ..

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

/IMFoption doesnot work .it does not kill notepad..while /IMoption actually works

/IMF选项不起作用。它不会杀死记事本..而/IM选项实际上有效

回答by BullyWiiPlaza

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

使用以下类来终止 Windows 进程如果它正在运行)。我正在使用 force 命令行参数/F来确保该/IM参数指定的进程将被终止。

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