[英]Kill a process based on PID in Java
到目前为止我有这个:
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 标志?
所以如果我有
Runtime.getRuntime().exec("taskkill /F /PID 827");
如何用我的 tokill 变量替换“827”?
只需构建字符串即可终止进程:
String cmd = "taskkill /F /PID " + tokill;
Runtime.getRuntime().exec(cmd);
我现在不坐在 Windows 电脑前。 但是如果tasklist
适合你,你可以使用ProcessBuilder来运行 windows 命令taskkill 。 使用ProcessBuilder
实例cmd /c taskkill /pid %pid%
像这样调用taskkill
(用实际的 pid 替换 %pid%)。 您不需要两个可执行文件的绝对路径,因为c:/windows/system32
位于路径变量中。
正如埃里克(在对您的问题的评论中)指出的那样,以前有很多人有这个答案。
String cmd = "taskkill /F /T /PID " + tokill;
Runtime.getRuntime().exec(cmd);
如果您使用的是 Windows,请使用 taskkill。
您可能希望使用 /T 选项来终止所有衍生的子进程。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.