Jan Zyka
Jan Zyka

Reputation: 17898

Ensure program runned via Runtime.exec() will die together with the java app

in my java program I am calling external program via Runtime.exec and calling Process.waitFor to wait for its completion. This is some long-running script. I want to ensure that if anything goes wrong with my java app (e.g. gets killed from outside for example, which btw. really happens from time to time in my case) the external running script will die as well.

I had a look on the Runtime.addShutdownHook which might be appropriate for this, but it clearly states that for example on SIGKILL no guarantee can be made whether the shutdownhook will or won't run.

Is there any other way how to ensure an external program runned from Java will die together with the calling java process?

Thanks

Upvotes: 3

Views: 325

Answers (1)

Arne Deutsch
Arne Deutsch

Reputation: 14769

If "Runtime.addShutdownHook" is not sufficien I think from the java side you are out of luck. Some ideas:

  1. your script can test if the java app is still running and terminating if needed
  2. let your java app update a file with a timestamp and let your script check periodically if the timestamp is to old (and terminate)
  3. Edit: launch another process which only monitors the java app and the script and kills the script is the java app is gone (of course if THIS process is killed you are out of luck again)

Upvotes: 1

Related Questions