// $Id: SignalInterceptor.java,v 1.1 2005/03/05 18:32:53 Dave Exp $ /* * SignalInterceptor.java * Copyright (C) 2005 David Clausen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later * version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the * Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package net.dclausen.util; /** *
* A simple wrapper around the undocumented and unsupported
* sun.misc.Signal* classes which are present in most JVM
* implementations. It can be used to trap OS signals such as SIGINT, SIGTERM,
* and SIGHUP on these JVMs.
*
* SignalInterceptor provides a level of indirection
* between your code and sun.misc.SignalHandler which can
* be useful for the following reasons:
*
sun.misc.Signal* classes are not available, throwing a checked
* exception out of the register method, rather than awkward
* LinkageErrors durring class initialization.* Some possible uses of this class are: *
*java.util.logging package closes all of its files in its
* ShutdownHook, which means your ShutdownHook might not be able to log
* anything. Note that you would still need to deal with
* System.exit(), but there is a different hack available for
* that ;).
* Register for the given signal. Note that the signal name should
* not begin with SIG. For example, if you are interested in
* SIGTERM, you should call register("TERM").
*
* If the registration fails for any reason, a
* SignalInterceptorException will be thrown. This is usually
* caused by one of the following conditions:
*
sun.misc.Signal* classes are not available (e.g.
* you are not using Sun's JVM).signame is not a valid trappable signal name on this
* OS (e.g. KILL can't be trapped, HUP does not exist on
* Windows)signame because it is
* already being used for some other important purpose (e.g. QUIT
* and/or BREAK cause the JVM to print diagnostic output).register(String) which never throws an
* exception. Instead, it returns true if registration
* succeeded, and false if it failed.
*/
protected boolean registerQuietly(String signame) {
try {
register(signame);
} catch (Throwable e) {
return false;
}
return true;
}
/**
* Handle the given signal (which you had previously registered for). If
* this method return false, or throws an exception, subsequent handlers
* in the chain will not be called.
*/
protected abstract boolean handle(String signame);
}