2

Existe algún tipo de librería para realizar tratamiento de señales en Java? Lo que para C sería algo así como:

if (signal(SIGINT, polear) == SIG_ERR) exit(0);

O para poder definir tus propias señales, del tipo: Ctrl+c = Signal_1.

0

1 respuesta 1

2

El tratamiendo de señales de Java es bastante pobre, prácticamente el API pública se reduce a dejarte hacer lo siguiente:

Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
    public void run() {
        // Hacer cosas cuando se recibe un SIGHUP, SIGINT o SIGTERM
    }
}));

De la API:

Once the shutdown sequence has begun it can be stopped only by invoking the halt method, which forcibly terminates the virtual machine.

Once the shutdown sequence has begun it is impossible to register a new shutdown hook or de-register a previously-registered hook. Attempting either of these operations will cause an IllegalStateException to be thrown.

Shutdown hooks run at a delicate time in the life cycle of a virtual machine and should therefore be coded defensively. They should, in particular, be written to be thread-safe and to avoid deadlocks insofar as possible. They should also not rely blindly upon services that may have registered their own shutdown hooks and therefore may themselves in the process of shutting down. Attempts to use other thread-based services such as the AWT event-dispatch thread, for example, may lead to deadlocks.

Shutdown hooks should also finish their work quickly. When a program invokes exit the expectation is that the virtual machine will promptly shut down and exit. When the virtual machine is terminated due to user logoff or system shutdown the underlying operating system may only allow a fixed amount of time in which to shut down and exit. It is therefore inadvisable to attempt any user interaction or to perform a long-running computation in a shutdown hook.

Básicamente, cuando la JVM se va a cerrar de forma correcta (gracefully), lanzará en un orden no predeterminado todos los hilos (Threads) que hayan sido registrados. Una vez que el proceso de cierre (shutdown) empieza, no se pueden añadir más hilos.

Los hilos deben estar programados defensivamente para evitar bloqueos (deadlocks) y deberían terminar rápidamente, para evitar que el sistema operativo considere que el proceso está colgado y fuerce el cierre (con un SIGKILL, supongo)

El API no pública (clases internas del JRE que no deberíamos usar para evitar problemas) incluye algunas clases mal documentadas como sun.misc.Signal y la interfaz sun.misc.SignalHandler, que permiten cosas como:

import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.lang.reflect.*;

// Application Wrapper
// usage: java AppWrap <app name> <app arg1> ... <app argn>
// where: <app name> is the name of the wrapped application class
//                   containing a main method
//        <app arg1> ... <app argn> are the application's arguments
class AppWrap {
    public static void main(String[] args) {
        try {
            // Install diagnostic signal handler
            DiagSignalHandler.install("ALRM");

            // Get the passed application's class
            Class wrappedClass = Class.forName(args[0]);

            // Setup application's input arguments
            String wrappedArgs[] = new String[args.length-1];
            for (int i = 0; i < wrappedArgs.length; i++) {
                wrappedArgs[i] = args[i+1];
            }

            // Get the main method for the application
            Class[] argTypes = new Class[1];
            argTypes[0] = wrappedArgs.getClass();
            Method mainMethod = wrappedClass.getMethod("main", argTypes);

            // Invoke the application's main method
            Object[] argValues = new Object[1];
            argValues[0] = wrappedArgs;
            mainMethod.invoke(wrappedClass, argValues);

        } catch (Exception e) {
            System.out.println("AppWrap exception "+e);
        }
    }
}

class DiagSignalHandler implements SignalHandler {

    private SignalHandler oldHandler;

    // Método estático para installar el signal handler
    public static DiagSignalHandler install(String signalName) {
        Signal diagSignal = new Signal(signalName);
        DiagSignalHandler diagHandler = new DiagSignalHandler();
        diagHandler.oldHandler = Signal.handle(diagSignal,diagHandler);
        return diagHandler;
    }

    // Signal handler method
    public void handle(Signal sig) {
        System.out.println("Diagnostic Signal handler called for signal "+sig);
        try {
            // Output information for each thread
            Thread[] threadArray = new Thread[Thread.activeCount()];
            int numThreads = Thread.enumerate(threadArray);
            System.out.println("Current threads:");
            for (int i=0; i < numThreads; i++) {
                System.out.println("    "+threadArray[i]);
            }

            // Chain back to previous handler, if one exists
            if ( oldHandler != SIG_DFL && oldHandler != SIG_IGN ) {
                oldHandler.handle(sig);
            }

        } catch (Exception e) {
            System.out.println("Signal handler failed, reason "+e);
        }
    }
}

Más detalles en esta página, pero realmente no hay mucho más.

1
  • Muchas gracias. Realmente pensaba que en este sentido se podía hacer algo más con Java. Commented el 23 feb. 2018 a las 11:37

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.