Table of Contents Previous Next
Logo
Threads and Concurrency with C++ : 31.10 Portable Signal Handling
Copyright © 2003-2010 ZeroC, Inc.

31.10 Portable Signal Handling

 
The IceUtil::CtrlCHandler class provides a portable mechanism to handle Ctrl+C and similar signals sent to a C++ process. On Windows, IceUtil::CtrlCHandler is a wrapper for SetConsoleCtrlHandler; on POSIX platforms, it handles SIGHUP, SIGTERM and SIGINT with a dedi­cated thread that waits for these signals using sigwait. Signals are handled by a callback function implemented and registered by the user. The callback is a simple function that takes an int (the signal number) and returns void; it should not throw any exception:
namespace IceUtil {

    typedef void (*CtrlCHandlerCallback)(int);

    class CtrlCHandler {
    public:
        CtrlCHandler(CtrlCHandlerCallback = 0);
        ~CtrlCHandler();

        void setCallback(CtrlCHandlerCallback);
        CtrlCHandlerCallback getCallback() const;
    };
}
 
The member functions of CtrlCHandler behave as follows:
• constructor
Constructs an instance with a callback function. Only one instance of Ctrl­CHandler can exist in a process at a given moment in time. On POSIX plat­forms, the constructor masks SIGHUP, SIGTERM and SIGINT, then starts a thread that waits for these signals using sigwait. For signal masking to work properly, it is imperative that the CtrlCHandler instance be created before starting any thread, and in particular before initializing an Ice commu­nicator.
• destructor
Destroys the instance, after which the default signal processing behavior is restored on Windows (TerminateProcess). On POSIX platforms, the “sigwait” thread is cancelled and joined, but the signal mask remains unchanged, so subsequent signals are ignored.
• setCallback
Sets a new callback function.
• getCallback
Gets the current callback function.
It is legal specify a value of zero (0) for the callback function, in which case signals are caught and ignored until a non-zero callback function is set.
A typical use for CtrlCHandler is to shutdown a communicator in an Ice server (see Section 8.3.1).

Table of Contents Previous Next
Logo