Class Signals
The Signals class provides utilities for registering and handling system signals in a platform-independent way. It allows terminal applications to respond to signals such as SIGINT (Ctrl+C), SIGTSTP (Ctrl+Z), and others, without having to use platform-specific code.
This class uses reflection to access the underlying signal handling mechanisms of the JVM, which may vary depending on the platform and JVM implementation. It provides a consistent API for signal handling across different environments.
Signal handling is particularly important for terminal applications that need to respond to user interrupts or that need to perform cleanup operations when the application is terminated.
- Since:
- 3.0
-
Method Summary
Modifier and TypeMethodDescriptionstatic Object
Registers a handler for the specified signal.static Object
register
(String name, Runnable handler, ClassLoader loader) static Object
registerDefault
(String name) static void
unregister
(String name, Object previous)
-
Method Details
-
register
Registers a handler for the specified signal.This method registers a handler for the specified signal. The handler will be called when the signal is received. The method returns an object that can be used to unregister the handler later.
Signal names are platform-dependent, but common signals include:
- INT - Interrupt signal (typically Ctrl+C)
- TERM - Termination signal
- HUP - Hangup signal
- CONT - Continue signal
- STOP - Stop signal (typically Ctrl+Z)
- WINCH - Window change signal
Example usage:
Object handle = Signals.register("INT", () -> { System.out.println("Caught SIGINT"); // Perform cleanup }); // Later, when no longer needed Signals.unregister("INT", handle);
- Parameters:
name
- the signal name (e.g., "INT", "TERM", "HUP")handler
- the callback to run when the signal is received- Returns:
- an object that can be used to unregister the handler
- See Also:
-
register
-
registerDefault
-
unregister
-