Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 694
Jan Zyka Avatar asked Dec 05 '25 04:12

Jan Zyka


1 Answers

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)
like image 172
Arne Deutsch Avatar answered Dec 07 '25 19:12

Arne Deutsch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!