I am almost certain this is impossible, but it's worth a try.
I am writing a command line interface for a certain tool. I am talking about a Java application that invokes another Java application. The tool calls System.exit
after execution, which in turn terminates my own execution environment. I don't want that.
Is there any way to ignore System.exit
calls?
The main alternative is Runtime. getRuntime(). halt(0) , described as "Forcibly terminates the currently running Java virtual machine". This does not call shutdown hooks or exit finalizers, it just exits.
exit(0) : Generally used to indicate successful termination. exit(1) or exit(-1) or any other non-zero value – Generally indicates unsuccessful termination. Note : This method does not return any value. The following example shows the usage of java.
Status code other than 0 in exit() method indicates abnormal termination of code. goto does not exist in Java, but it supports labels. It is better to use exception handling or plain return statements to exit a program while execution.
System. exit() method. This method terminates the currently running Java Virtual Machine(JVM). It takes an argument “status code” where a non zero status code indicates abnormal termination.
Yes, this is possible using a SecurityManager. Try the following
class MySecurityManager extends SecurityManager { @Override public void checkExit(int status) { throw new SecurityException(); } @Override public void checkPermission(Permission perm) { // Allow other activities by default } }
In your class use the following calls:
myMethod() { //Before running the external Command MySecurityManager secManager = new MySecurityManager(); System.setSecurityManager(secManager); try { invokeExternal(); } catch (SecurityException e) { //Do something if the external code used System.exit() } }
You can break your application in two parts. The first one gets started by the tool. Then you launch the second part of your application as a new process. Then the host application kills your first part, but the second part is still running.
This way the first part of your app is just the startup for the second part which is in turn your real application.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With