Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent calls to System.exit() from terminating the JVM?

Tags:

java

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?

like image 609
Tiago Veloso Avatar asked Apr 05 '11 09:04

Tiago Veloso


People also ask

What can I use instead of system exit in Java?

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.

Does System Exit 0 terminate the program?

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.

What can be used instead of system Exit 0?

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.

What is System exit () used for?

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.


2 Answers

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()     } } 
like image 153
theomega Avatar answered Sep 20 '22 19:09

theomega


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.

like image 23
codymanix Avatar answered Sep 17 '22 19:09

codymanix