简体   繁体   English

如何杀死一个悬空的Java程序(在Windows中)?

[英]How can I kill a Java program that is left hanging (in Windows )?

Suppose that in Java I have a simple Echo Client/Server pair. 假设在Java中,我有一个简单的Echo Client / Server对。 I start up the Server process, but I never actually start the Client process. 我启动了Server进程,但实际上从未启动过Client进程。

What I'd like to do, is have a third program (call it "Parent"), that will automatically kill this Server program after 30 seconds of being idle. 我想要做的是拥有第三个程序(称为“父程序”),该程序将在闲置30秒后自动终止该Server程序。

Could I use Powershell to do this? 我可以使用Powershell来做到这一点吗? Or do I need to use C or other programming? 还是我需要使用C或其他程序?

Yes, as long as you have a good way to: 1) uniquely identify the server process 2) determine server is idle 是的,只要您有一个好的方法即可:1)唯一标识服务器进程2)确定服务器空闲

If there will never be two (or more) instances of the server process, then you can identify the process by name (make sure your process has a unique name!) 如果永远不会有两个(或更多)服务器进程实例,则可以按名称标识该进程(确保您的进程具有唯一的名称!)

Determining that the server is idle may be tricky (hence the comments to implement the server stopping itself without resorting to a "parent" process). 确定服务器处于空闲状态可能很棘手(因此,在不使用“父”进程的情况下,实现服务器停止自身的注释)。 However if the server is memory or CPU intensive when it is active you may be able to take advantage of that to distinguish idle from busy. 但是,如果服务器处于活动状态时服务器占用大量内存或CPU,则可以利用它来区分空闲还是繁忙。 You can use get-process (gps) to determine the process' current CPU and memory use. 您可以使用get-process (gps)来确定进程当前的CPU和内存使用情况。 The trick will be to know how long it's been idle if it currently looks idle. 诀窍是要知道当前空闲状态空闲了多长时间。 To do this reliably you will need to poll with gps more frequently than it takes the server to process a request. 为了可靠地做到这一点,您需要比使用服务器处理请求更频繁地轮询gps Otherwise you may poll before the server is busy, then the server is busy, and then you poll again when it's idle. 否则,您可以在服务器繁忙之前进行轮询,然后在服务器繁忙之前进行轮询,然后在服务器空闲时再次进行轮询。 But you'll think it was idle the whole time. 但是您会认为它一直都是闲置的。

You can avoid the dilemma above by having the server change something when it knows it has been idle for 30 seconds, like the window title. 您可以通过让服务器在知道空闲30秒后更改某些内容来避免上述难题,例如窗口标题。 (But if you're doing that why not just have the server terminate itself?) (但是,如果这样做,为什么不让服务器自行终止呢?)

Once the PS script determines the server is idle then get-process -name yourServerProcess|stop-process will stop the server process. 一旦PS脚本确定服务器处于空闲状态,则get-process -name yourServerProcess|stop-process将停止服务器进程。 Specify "yourServerProcess" without the .EXE at the end. 指定“ yourServerProcess”,结尾不带.EXE。 If you get a permissions error, then run PS as administrator. 如果出现权限错误,请以管理员身份运行PS。

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

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