简体   繁体   English

如何在Java中杀死特定进程

[英]How to kill a particular process in java

Hi all i Have two process in my java application as below. 大家好,我在Java应用程序中有以下两个过程。

Process p1=some process;
Process p2=some process;

At the first time it starts its working perfectly.But when i reload the application the older process is also running so i just want to kill the older process if its executing.I know that we can kill a process by using its process id.But how can i get the process id of this p1 and p2.Any idea?. 第一次启动时,它可以完美运行。但是,当我重新加载应用程序时,旧进程也正在运行,所以我只想杀死执行中的旧进程。我知道我们可以通过使用其进程ID杀死一个进程。我怎么能得到这个p1和p2的进程ID?

Catch the reload event in your application and terminate the child process before you exit. 在您的应用程序中捕获reload事件,并在退出前终止子进程。

If that doesn't work, you probably have a bug in your design. 如果这不起作用,则说明您的设计中可能存在错误。 Try to fix that bug. 尝试修复该错误。 Really. 真。 I mean it. 我是认真的。

A workaround is to write the PID into a text file. 解决方法是将PID写入文本文件。 When you start, read the text file, check if this is the correct process and then kill it. 开始时,请阅读文本文件, 检查是否正确 ,然后将其杀死。

Without the check, you might be killing a perfectly valid process which was created by someone else. 没有检查,您可能会杀死别人创建的完全有效的进程。 My reasoning is like so: You can't kill the process when you reload. 我的推理是这样的:重新加载时您无法终止该进程。 That means you can't delete the text file either. 这意味着您也不能删除文本文件。 So the PID file will always exist. 因此,PID文件将始终存在。 Eventually, you will kill the wrong process. 最终,您将杀死错误的过程。 That will happen once per year. 那将每年发生一次。 It will happen the first time six months after you left/changed job/etc. 这将在您离开/更换工作等六个月后第一次发生。 Nobody will understand what is going on because it's almost impossible to reproduce. 没有人会知道发生了什么,因为几乎不可能复制。

As others have said, it would be better to terminate the process in a more natural way. 正如其他人所说,最好以一种更自然的方式终止该过程。

However, if you do need to actually forcibly terminate it, then you could call the destroy() method on the Process object, whenever you don't care about it running anymore. 但是,如果确实需要强行终止它,则可以在不再关心它运行时都可以在Process对象上调用destroy()方法。

Also, do you really need to run the code as a Process? 另外,您是否真的需要将代码作为流程运行? There are generally better ways. 通常有更好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM