在Java中杀死基于PID的进程

时间:2012-03-05 20:43:43

标签: java windows process

到目前为止,我有这个:

public static void main(String[] args) {

    try {
        String line;
        Process p = Runtime.getRuntime().exec(
                System.getenv("windir") + "\\system32\\" + "tasklist.exe");

        BufferedReader input = new BufferedReader(new InputStreamReader(
                p.getInputStream()));

        while ((line = input.readLine()) != null) {
            System.out.println(line); // <-- Parse data here.
        }
        input.close();
    } catch (Exception err) {
        err.printStackTrace();
    }

    Scanner killer = new Scanner(System.in);

    int tokill;

    System.out.println("Enter PID to be killed: ");

    tokill = killer.nextInt();

}

}

我希望能够根据用户输入的PID终止进程。我怎样才能做到这一点? (只需要在Windows上工作)。 *注意:必须能够杀死任何进程,inc。 SYSTEM进程,所以我猜测如果使用taskkill.exe来执行此操作将需要-F标志?

所以,如果我有

Runtime.getRuntime().exec("taskkill /F /PID 827");

如何将“827”替换为我的tokill变量?

4 个答案:

答案 0 :(得分:6)

只需构建字符串即可终止进程:

String cmd = "taskkill /F /PID " + tokill;
Runtime.getRuntime().exec(cmd);

答案 1 :(得分:2)

我现在不坐在Windows电脑前。但如果tasklist适用于您,则可以使用ProcessBuilder来运行Windows命令taskkill。使用taskkill实例ProcessBuilder调用此类cmd /c taskkill /pid %pid%(将%pid%替换为实际的pid)。您不需要两个可执行文件的绝对路径,因为c:/windows/system32位于路径变量中。

埃里克(在对你的问题的评论中)指出,之前有很多人有这个答案。

答案 2 :(得分:0)

String cmd = "taskkill /F /T /PID " + tokill;
Runtime.getRuntime().exec(cmd);

如果您使用的是Windows,请使用taskkill。

您可能想使用/ T选项杀死所有产生的子进程。

答案 3 :(得分:0)

JavaSysMon库可以做到这一点,并且具有多平台优势:https://github.com/danielflower/javasysmon (原始版本的叉子,它有一个方便的maven构件)

private static final JavaSysMon SYS_MON = new JavaSysMon();

// There is no way to transform a [Process] instance to a PID in Java 8. 
// The sysmon library does let you iterate over the process table.
// Make the filter match some identifiable part of your process and it should be a good workaround
int pid = Arrays.stream(SYS_MON.processTable())
    .filter(p -> p.getName().contains("python"))
    .findFirst().get().getPid()

// Kill the process
SYS_MON.killProcess(pid);
// Kill the process and its children, or only the children
SYS_MON.killProcessTree(pid, descendentsOnly);
相关问题