Disabling System.exit() and shutdown calls

I am trying to splice/hack together something that might stop a System.exit(0) call or perhaps some type of exit call for a Java application. The only thing I have come up with now is making an extension of SecurityException and putting the shutdown code within a try. Here is what I have so far...
class ExitTrappedException extends SecurityException {
     protected static void forbidSystemExitCall() {
          final SecurityManager securityManager = new SecurityManager() {
               public void checkPermission( java.security.Permission permission ) {
                    if( "exitVM".equals( permission.getName() ) ) {
                         throw new ExitTrappedException() ;
          System.setSecurityManager( securityManager ) ;
     protected static void enableSystemExitCall() {
          System.setSecurityManager( null ) ;
}And then utilizing it in the following manner...
forbidExitCall() ;
    try {
      // Call the "exiting" code here...
    } catch( ExitTrappedException e ) {
    } finally {
      enableExitCall() ;
    }I am not very comfortable setting the SecurityManager to null when re-enabling it to be honest. I am curious if someone might have a different solution to stopping a System.exit(0) call and the windows altf4+ shortcut. Any help would be much appreciated.

     static SecurityManager securityDefault = System.getSecurityManager();
     protected static void forbidSystemExitCall() {
          final SecurityManager securityManager = new SecurityManager() {
               public void checkPermission( java.security.Permission permission ) {
                    if( "exitVM".equals( permission.getName() ) ) {
                         throw new ExitTrappedException() ;
          System.setSecurityManager( securityManager ) ;
     protected static void enableSystemExitCall() {
          System.setSecurityManager( securityDefault ) ;
}how bout that?
Edited by: brillohead on Aug 4, 2008 11:21 AM

Similar Messages

  • Intercepting System.exit() and System.out.println() calls

    hi there,
    I have often problems when working with code that uses System.exit() and System.out.println() extensively, because it becomes difficult to debug.
    Basically I do have wrappers for System.exit() (my own static exit function) and for System.out.println() (log4j).
    Still not all programmers are using these methods; Probably the only way to enforce this is some kind of code warrior, but I was hoping to be able to intercept the two System.XXX calls (and throw an appropriate Exception). is this possible ??

    Why not simply make your own security manager andhandle checkExit() and checkWrite?
    Does anyone have a simple example of this? Please?System.exit() can be intercepted using a security manager, but not System.out.xxx.
    Here is a short example:
    //set your security manager
    static{
         SecurityManager s = new OwnSecurityManager();
         System.setSecurityManager(s);
    //redirect the out stream
    try{
         PrintStream ps = new PrintStream(new FileOutputStream("output.txt"));
         System.setOut(ps);
    }catch(IOException ioe){
         ioe.printStackTrace();
    //some tests
    System.out.println("Test");
    System.exit(2);
    //your security manager
    class OwnSecurityManager extends SecurityManager{
         public void checkExit(int code){
           if(code > 0){
             super.checkExit(code);
             throw new SecurityException("Not allowed here->" + code);
         public void checkRead(FileDescriptor fd){
         public void checkRead(String file){
         public void checkRead(String file, Object context){
         public void checkPermission(Permission perm){
           if(perm.getName().equals("exitVM")){
             System.out.println("exitVM");
    }

  • Error in XMLDiff Bean, System.exit() is being called in setFiles() ?

    When I call the setFiles() method in XMLDiff and the files contain dtd references, my application will shut down competely as though System.exit() is being called from within the XMLDiff bean. I have tested this with the XMLDiff demo and it also shut down when a dtd reference was in the files.

    The version of XDK is 9.2.0.2.0
    The test case is the "family.xml" in the demo\java\parser\common directory using the XMLDiffSample application. What I did was to try to compare the family.xml against itself. When I do that it shuts down the demo application as though System.exit() has been called.
    Setting the standalone="yes" did in fact cause it to work properly, but I am not sure why?

  • Lion disables system info and software update in about this mac

    hey guys I have problem with lion when I reboot lion,
    it disables system info and software update in "about this mac"
    actually it says "this button is disabled because there is no system profiler application" or  "this button is disabled because there is no software update application"
    and also everytime when I reboot my computer it always changes default applicatons. for example
    it changes from VLC player to quicktime,  from Archive utility to textEdit and so on.
    each time i got to reinstall "Afloat application" if i want to use it.
    for making them ok I just need to open software updater from system pref. and the button becomes visible again.
    it is same with the system info. I gotto search system profiler via spotlight search and I run, button becomes visible again.
    for the archieve utility i got to go to coreservices and open Archieve utility then automatically it becomes default app for .zip files again.
    /___sbsstatic___/migration-images/170/17091900-1.png
    http://imageshack.us/photo/my-images/689/screenshot20111225at659.png/

    Did you just install Lion? If so, you might need to try to reinstall as something got messed up.
    Alfoat uses SIMBL which will break at just about every update. The reason you may have to keep installing Afloat is because the Resume feature of Lion is not compatible with SIMBL. See here: http://roaringapps.com/app:383
    SIMBL is a low-level system hack and may be causing your problems.

  • Is System.exit() a good call to use?

    I have a program that checks for updates in the db. If there are no updates in the database I want the program to stop. There are also many other conditions that would cause the program to stop. None of them are "Errors" so I wasn't using Exceptions to end the program The program runs from a command line or from chron job. Is it safe / OK to use System.exit() to do this?

    As you describe it, I'd say yes. System.exit() is the way to end your program.
    The danger of System.exit() is if a class you write will be reused in some other system. In that case, System.exit() could be entirely inappropriate in that context, thus preventing your class from being reusable.
    If you only call System.exit() in your main() method, you'll probably be OK.

  • Disabled System Profile and Disk Utility

    I have just acquired an Ibook G4, unfortunately without any operating disks. If I try to go into the System Profile or Disk Utility I am told that this may be disabled or not installed. Will an installation of a new operating system, probably Leopard as that's the easiest one to get hold of, resolve this issue?

    Either Tiger or Leopard. So long as they are full retail installers
    and not someone else's old system disc for a specific computer
    you do not happen to also have. Being careful to get one that
    can install on any compatible and supported computer is best.
    If you had the correct disc as was missing, a utility such as one
    known as Pacifist could be used to get only the parts you need
    from the correct install disc, and those could be put in separately.
    In the absence of that, a full and totally new installation is one
    way to be sure the drive can be tested (booted Disk Utility, zero
    data on drive, reformat, install all new from scratch) & be good.
    The nice thing about Tiger, if you can find someone who has
    upgraded to Leopard and has a 'retail Tiger installer set' to
    give you or sell at a low price, that is a good system and it
    has all the other parts to upgrade from the retail installer,
    on the internet. And any issues in Tiger are solved.
    Since you do not have the original software packet which
    the computer came with when new, some of the apps in
    the computer now won't be in there if you do a major and
    proper all-new installation of the new system on a wiped
    or totally erased (over-written with zeros from the booted
    full installer disc's Disk Utility options, then reformatted to
    HFS+ or Apple Partition Map, then full system installed)
    the old stuff from prior generations of use will be gone.
    So will the old AppleWorks application and a few other
    nice but no longer available items. The new iWorks is
    a suitable replacement for AppleWorks in some ways;
    and the free NeoOffice is adequate if you need an app
    somewhat like MS Office X.
    Without the OS X Installer disc set for the system in
    the computer you have, you can't repair it nor can a
    reset of the password or change of other features
    be done properly. If the account you are using on it
    is not an admin user account, some settings may
    have been reduced for some lesser user level. And
    if someone damaged the system somehow by taking
    parts of the OS X out of the folders, it would need
    at least an 'archive & install' with that old installer.
    So, you can make use of the computer if you have a
    full retail installer disc and the computer is supported.
    There are requirements to be met for various systems
    to work in a variety of computers, so you may need to
    read in Support to see what the minimum requirement
    is, for the OSX version you may get a deal on.
    There may be other options, but they should start with
    the proper install disc that is missing in the first place!
    Good luck & happy computing!

  • Kill and System.exit

    Is there a way (with Linux) to issue the kill command on your java process so that System.exit(0) is called and you know that your shutDownHooks will run?

    Thanx again for the reply, Freddy
    first things first:
    System.exit(0) does not work in this case..
    and the code is reached..
    // main class
    public class AdminApp {
    public AdminApp() {
    public static void main(String[] args) {
    AdminApp adminApp1 = new AdminApp();
    AdminFrame frame = new AdminFrame();
    /// admin frame class
    public class AdminFrame extends JFrame{
    public AdminFrame() {
    addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    this.pack();
    this.setSize(600,480);
    this.setVisible(true);
    groupsMenuItem.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    desktop.add(new AdminGroups());
    //admingroups class
    public class AdminGroups extends JInternalFrame {
    private JTextArea textArea = new JTextArea();
    private JScrollPane scrollPane = new JScrollPane();
    JPanel groupPanel = new JPanel();
    XYLayout xYLayout1 = new XYLayout();
    public AdminGroups() {
    setSize(200,300);
    setTitle("Edit Text");
    setMaximizable(true);
    setIconifiable(true);
    setClosable(true);
    setResizable(true);
    scrollPane.getViewport().add(textArea);
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(scrollPane,BorderLayout.CENTER);
    try {
    jbInit();
    catch(Exception e) {
    e.printStackTrace();
    getContentPane().add(groupPanel);
    private void jbInit() throws Exception {
    groupPanel.setLayout(xYLayout1);
    }

  • How  to track System.exit(0) call

    hi there,
    how can i trace the System.exit(0) function call in my program.
    i.e as we know which class is being loaded into the jvm by overriding
    the classloader, can we similarly know when is our jvm going to be
    destroyed. here iam invoking jvm from my windows program using invocation api.
    any help is mostly appreciated.
    thanks in advance
    bye
    ramana

    Not sure I know what you are asking.
    You could create a security manager which prevents exit() from being called.
    You could replace System using the bootstrap command line option. Although if you do that you can not distribute it due to the license agreement. Once replaced you can do anything you want in the application.
    You could use Runtime.addShutdownHook() if you just want to do something when the application exits.

  • System.exit(o) in Swing

    Hi,
    In my Swing application, as soon as I start the main() method, a dialog containing Username and Password fields with OK and Cancel buttons gets popped-up. I have a propertyChangeListener which gets notified when Ok or cancel is pressed and when Cancel is pressed, System.exit(0) is called to exit the JVM.
    So, there are two threads running -
    One - the main thread which invokes the dialog pop-up
    Second - the propertychangelistener which calls the System.exit(0) on pressing Cancel button.
    So, at times, after pressing cancel button, the application does not exit but invokes the previously running thread (main thread). But this does not happen always.
    Could you please let me know why the application does not terminate completely and how to resolve this?
    Thanks in advance!

    Hi,
    As I had already mentioned in my previous post -
    Here is the pseudo-code which fails to terminate on pressing Cancel button at times.
    ================The Login dialog code=============
    public LoginDialog()
    // Other code
    JOptionPane optionPane = new JOptionPane(array, JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION, null, options, options[0]);
    optionPane.addPropertyChangeListener(new PropertyChangeListener()
    public void propertyChange(PropertyChangeEvent e)
              Object value = optionPane.getValue();
              if (value.equals(YES))
              else
    // user closed dialog or clicked cancel
    setVisible(false);
    System.exit(0);
    ===============The main thread===================
    This main() method calls the logindialog with username and passwrd as parameters.
    So, initially, the main() thread is started and the login dialog is displayed. On pressing Cancel in this dialog, the control goes to propertyChangeListener of the loginDialog() and calls System.exit(0) which should terminate the entire application, but at times, the previously running main thread is resumed and the application is not terminated.
    Please clarify why this happens.
    Thanks in advance!!
    });

  • Exit from a Frame without resorting to System.exit()

    This is driving me nuts.
    I've got a really simple problem, actually... I've got a Frame and I'm trying to get rid of it so my application will exit.
    Though using System.exit() seems to be the most common way to get an application to exit, I'd prefer to avoid going that route. My program uses multiple threads, and I want to give them all a chance to exit gracefully before the application exits, as opposed to terminating them all quite suddenly. All the threads monitor a boolean value, "exiting", and terminate, after some cleanup, when the variable is set. Using join() on all the threads before using System.exit() would work, except any number of threads may be created by the program, and not all of them will be accessible by the function doing the exiting!
    If I simply omit the call to System.exit(), and remove the Frame with dispose(), the threads all shut down properly, and the program appears to have exited, except the command prompt doesn't reappear until I hit Ctrl-C.
    So I looked up the docs for the dispose() method. It was slightly different than I remembered... Obviously, that method is not the way to shut down a Frame. What is?

    So I looked up the docs for the dispose() method. It
    was slightly different than I remembered...
    Obviously, that method is not the way to shut down a
    Frame. What is?The problem is that once you use some GUI, a pool of AWT threads is created and they are not shut down, not even if there is no more GUI visible.
    Look at these other threads for some explanation on this behaviour an workarounds:
    http://forum.java.sun.com/thread.jspa?forumID=5&threadID=10901
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=122569

  • System Exit from JAVA Application

    I need to call Oracle Reports from a JAVA application.
    Does anyone have experience in this area?
    One thing that comes to mind is to make a system exit and call the reports from the command line. Is this possible to be done? How?
    Thank you for any help or suggestions.
    Tina.

    the best way to access the oracle database is via jdbc (see http://java.sun.com/products/jdbc/ ). if, however, you specifically need to run some oracle reporting s/w then you could run it as a separate process from your java application using Runtime.exec() (see http://java.sun.com/j2se/1.3/docs/api/java/lang/Runtime.html#exec(java.lang.String) ) which returns a Process object. you can then read its output with the Process object's getInputStream() method (this gives you an InputStream which is the data piped from the standard output stream of the process).
    hth,
    jonesy (sun developer technical support)

  • System.exit() causes Firefox to close

    Hi.
    I have a strange problem - I have an app which can be both an applet and a standalone application. At some point is calls System.exit() and it can happen in an applet too. (It's easy to redesign the code but that;s not my question)
    Strange enough (for me at least) the call causes the whole browser to close! (Observed in FF 1.5.x and 2.0, reported in IE7). Is this supposed to happen?
    Thanks.

    No, this isn�t a bug. You should not call System.exit from an applet, instead use the life cycle methods of the Applet class.

  • How do I exit a java program based on condition can i use system.exit

    I have java program that is called by another program that I dont have control on. My program returns a bigdecimal... but if the ordernumber is empty in my program i dont wnat to do anything.. does system.exit work in that condition... i put it int he else if ordernumber is empty condition.. but i dont think that is the right approach..

    When software module is expected to bring some result, it should bring the result, positive or negative. I think you should check what your counterpart software expects as positive or negative result. And then implement your software this way. You can use System.exit, but this call is employed usually to indicate status with the software after it's completion and not to return any resulting value.
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/System.html#exit(int)

  • How to determine the system color and set them for my app?

    Hi,
    I'd like to set the colors of my application to the system's colors. Especially the backgrounds of my JPanels, JButtons and so on should look like in the operating system. If you change the systems color scheme, my application looks really wierd with it's grey canvas an components and the border and menu of the window is displayed in the system's colors.
    any idea??
    koem

    The UIManager only seems to have control over
    awt-controls. All swing controls are not listed, when
    you try this:
            UIDefaults defaults =
    UIManager.getLookAndFeelDefaults();
    for(Iterator i = defaults.keySet().iterator();
    ator(); i.hasNext();)
    String name = (String)i.next();
    System.out.println(name);
    }It would be nice to have it set globally somewhere in
    the program.
    koemActually, the truth is quite the opposite, the UIManager only has control over swing components.
    There are many ways you can set these globally. You can sublcass your own look and feel, use the system look and feel, call UIDefaults.put() etc.
    Graeme

  • To trap System.exit(0)

    Hi All,
    In one of our code we are saying System.exit(0),System.exit(1),System.exit(-1) based on certain condition that occur in the program. Could any one let us know how to trap the integer returned to the OS when System.exit(x) is called.
    Regards,
    Vinodramu

    Not sure I know what you are asking.
    You could create a security manager which prevents exit() from being called.
    You could replace System using the bootstrap command line option. Although if you do that you can not distribute it due to the license agreement. Once replaced you can do anything you want in the application.
    You could use Runtime.addShutdownHook() if you just want to do something when the application exits.

Maybe you are looking for

  • How to change Color of IMAGE Links

    Page properties is the only place I can find to change the color of LINKS. It works for text, but not for the border it automatically puts around a linked image. It's purple! Can't I make it white to blend in with the background? I have already chang

  • Trap Error in DIAdem through ToCommand

    Can you let me know if there is any means to trap errors that would occur in DIAdem Interface when it's called through ToCommand and NoErrorDisplay is set to true (1)? We try to invoke DIAdem through ToCommand in a COM, since we need DIAdem to work a

  • JMenus and KeyboardFocusManager

    I'd like my menus to do different things depending on where focus was before the menu was invoked (ctrl/C should copy the appropriate string or object, for example). If the menu is invoked via the mouse, rather than a keyboard shortcut, it has the fo

  • Keep my LAPTOP Mounted in Finder

    I am having this annoying problem. I am frequently in a position of either moving data from my laptop to my desktop or desktop to laptop, or I am in the position of opening files on my desktop that are on my laptop or in the position of saving files

  • Windows Script Component Registration Generate 0x80004005 Error Code

    Scenario : I create a simple .hta for managing students information and personal data. I create an application registration system which is required by the user to register the .hta before using it (Freeware which required registration for software b