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

查看:437
本文介绍了使用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应用程序中启动进程(例如,通过调用运行时.exec() ProcessBuilder.start())然后你有一个有效的过程引用它,您可以在 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天全站免登陆