使用 Java 杀死进程 [英] Killing a process using Java

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

问题描述

我想知道如何杀死"已启动的进程.我知道 Process API,但我不确定,如果我可以使用它来杀死"已经运行的进程,例如 firefox.exe 等.如果可以使用 Process API,请您指出我正确的方向?如果没有,还有哪些其他可用选项?谢谢.

I would like to know how to "kill" a process that has started up. I am aware of the Process API, but I am not sure, If I can use that to "kill" an already running process, such as firefox.exe etc. If the Process API can be used, can you please point me into the correct direction? If not, what are the other available options? Thanks.

推荐答案

如果您从 Java 应用程序中启动进程(例如通过调用 Runtime.exec()ProcessBuilder.start()) 那么你就有了一个有效的 Process 引用,你可以在 Process 中调用 destroy() 方法> 类来终止该特定进程.

If you start the process from with in your Java application (ex. by calling Runtime.exec() or ProcessBuilder.start()) then you have a valid Process reference to it, and you can invoke the destroy() method in Process class to kill that particular process.

但请注意,如果您调用的进程创建了新的子进程,则这些子进程可能不会终止(请参阅 http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).

But be aware that if the process that you invoke creates new sub-processes, those may not be terminated (see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4770092).

另一方面,如果您想终止外部进程(您不是从 Java 应用程序中生成的),那么您可以做的一件事就是调用允许您执行此操作的 O/S 实用程序.例如,您可以在 Unix/Linux 下对 kill 命令尝试一个 Runtime.exec() 并检查返回值以确保应用程序被杀死或没有被杀死(0 表示成功,-1 表示错误).但这当然会使您的应用程序平台依赖.

On the other hand, if you want to kill external processes (which you did not spawn from your Java app), then one thing you can do is to call O/S utilities which allow you to do that. For example, you can try a Runtime.exec() on kill command under Unix / Linux and check for return values to ensure that the application was killed or not (0 means success, -1 means error). But that of course will make your application platform dependent.

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

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