Naftuli Kay
Naftuli Kay

Reputation: 91620

Can I have the JVM kill a started process when it exits?

I just realized that all of the processes I'm starting aren't dying when the JVM exits. Is there a way for me to close a Process with the JVM exits, kind of like File.deleteOnExit()?

Upvotes: 3

Views: 1285

Answers (2)

Michael Krussel
Michael Krussel

Reputation: 2646

You could keep a list of all running processes and then use Process.destroy() to shut them down inside a shutdown hook like Platinum Azure mentioned.

You also need to clean the list up when the processes are finished. If you have code that is already calling process.waitFor() then that could cleanup the list.

The destroy method forcibly shuts down the process, possibly corrupting anything it is doing, so you should take care with using it.

If you control the other processes, then signaling it to shutdown and then waiting for it to finish would be advisable over calling destroy.

Upvotes: 0

Platinum Azure
Platinum Azure

Reputation: 46183

You should call the .waitFor() method on each Process before exiting.

If you can't control that process as well as you'd like, you could use Runtime.addShutdownHook():

final Process process = startNewProcess();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    @Override
    public void run() {
        process.waitFor();
    }
}));

I really don't recommend the latter solution if possible, though. If the JVM doesn't have a chance to clean itself up, then the process will still be running if it is forcibly killed.

Upvotes: 3

Related Questions