The C++ class
CtrlCHandler provides a portable abstraction to handle CTRL-C and similar signals sent to a C++ process. On Windows,
CtrlCHandler is a wrapper for
SetConsoleCtrlHandler; on POSIX platforms, it handles
SIGINT with a dedicated thread that waits for these signals using
sigwait. Signals are handled by a callback function that you implement and register. The callback is a simple function that takes an
int (the signal number) and returns
void; it must not throw any exception.
CtrlCHandler does not terminate your application after running the registered callback (if any).
CtrlCHandler allows you handle CTRL-C and similar signals repeatedly.
The member functions of
CtrlCHandler behave as follows:
Constructs an instance with optionally a callback function. Only one instance of
CtrlCHandlercan exist in a process at a given moment in time. On POSIX platforms, the constructor masks
SIGINT, then starts a thread that waits for these signals using
sigwait. For signal masking to work properly, it is imperative that the
CtrlCHandlerinstance be created before starting any thread, and in particular before initializing an Ice communicator.
Destroys the instance, after which the default signal processing behavior is restored on Windows (
TerminateProcess). On POSIX platforms, the "sigwait" thread is terminated and joined, but the signal mask remains unchanged, so subsequent signals are ignored.
Sets a new callback function, and returns the old callback function.
Gets the current callback function.
It is legal to specify
nullptr for the callback function, in which case signals are caught and ignored until a non-null callback function is set.
A typical use for
CtrlCHandler is to shutdown a communicator in an Ice server. For example, you could use it as follows: