在 Java 中根据 PID 杀死进程 [英] Kill a process based on PID in Java

查看:68
本文介绍了在 Java 中根据 PID 杀死进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止我有这个:

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 上工作).*注意:必须能够杀死任何进程,包括SYSTEM 进程,所以我猜如果使用 taskkill.exe 执行此操作将需要 -F 标志?

I want to be able to kill a process based on the PID a user enters. How can I do this? (Only needs to work on Windows). *NB: Must be able to kill any process, inc. SYSTEM processes, so I'm guessing a -F flag will be needed if using taskkill.exe to do this?

所以如果我有

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

如何用我的 tokill 变量替换827"?

how can I replace "827" with my tokill variable?

推荐答案

只需构建字符串即可杀死进程:

Simply build the string to kill the process:

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

这篇关于在 Java 中根据 PID 杀死进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆