如何清理Java中打开的进程? [英] How do I cleanup an opened Process in Java?

查看:111
本文介绍了如何清理Java中打开的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从Java程序启动流程。我紧紧抓住它,然后在程序的后面,我可能会向它发送一些信号(不同于UNIX信号-一种不同的机制),告诉它清理和关闭自身,这是终止此过程的正确方法。以后我可能会重新启动并保留该进程,然后再次停止该进程任意次。

I'm starting a Process from a Java program. I hold onto it and at later points in the program I may send it some signals (not as in UNIX signals -- a different mechanism) to tell it to clean itself up and shut down, which is the proper way of terminating this process. I may later restart and hold onto the process and stop it again an arbitrary number of times.

我希望我的程序(如果存在)向该进程发出信号以通知终止并确保它存在。否则,由于Java异步启动了该过程,因此它会持续存在并在我的程序终止后继续运行。

I'd like my program, when it exists, to signal the Process to terminate and make sure it exists. Otherwise, since Java starts the process up asynchronously, it persists and continues to run after my program terminates.

我想我应该在包含以下内容的对象的析构函数中执行此操作Process变量,但是Java似乎没有析构函数。它有一个finalize()方法用于释放通过JNI分配的内存,但这不是这种情况,显然,您不能保证会调用finalize():仅当对象被垃圾回收时才调用finalize()。程序可能一直运行到终止而无需调用垃圾回收,在这种情况下,所有内容都立即被释放,并且没有垃圾回收并且没有finalize()发生。

I thought I would do this in the destructor for the object that contains the Process variable, but it seems that Java does not have a destructor. It has a finalize() method for freeing memory allocated through JNI, but this is not such a case, and apparently you can't guarantee that finalize() will be called: it is only called when the object is garbage collected, and the program might run through to termination without ever calling garbage collection, in which case everything is freed at once and no garbage collection and no finalize() occurs.

什么是最好的方法确保在我的程序退出时首先调用此清理代码?

What's the best way to make sure that when my program exits this cleanup code gets called first?

我看到Java 1.6引入了Runtime.addShutdownHook()方法,但我目前仍处于困境在Java 1.5上。

I see that Java 1.6 has introduced a Runtime.addShutdownHook() method, but I am currently stuck on Java 1.5.

推荐答案

Try / finally最接近C ++析构函数。

Try/finally is the closest that you will get toe a C++ destructor.

Process process;

process = ....;

try
{
    // do work
}
finally
{
    // send info to process to shut it down
}

此外, addShutdownHook已在1.3中添加 ...

这篇关于如何清理Java中打开的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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