How do I cleanup an opened Process in Java?

余生长醉 提交于 2019-12-11 04:24:42

问题


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.

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.

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?

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


回答1:


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
}

Also, addShutdownHook was added in 1.3...




回答2:


Why not call it before you call System.exit? Your code should probably be structured so you're only calling System.exit from one place (or returning from main), either way that would be a good way to go.



来源:https://stackoverflow.com/questions/727151/how-do-i-cleanup-an-opened-process-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!