分类:
2009-01-19 23:18:01
ace 组件学习(一)
信号处理组件的设计
1. 问题
传统信号处理流程
1) 定义各待捕获信号的处理函数
2) 定义全局变量
3) 传统的信号底层信号注册api
代码:
/* Global variables that control
process shutdown. */
sig_atomic_t graceful_quit = 0;
sig_atomic_t abortive_quit = 0;
/* Signal handler for SIGINT. */
void SIGINT_handler (int signum)
{
assert (signum == SIGINT);
graceful_quit = 1;
}
/* Signal handler for SIGQUIT. */
void SIGQUIT_handler (int signum)
{
assert (signum == SIGQUIT);
abortive_quit = 1;
}
/* ... */
int main (void)
{
struct sigaction sa;
sigemptyset (&sa.sa_mask);
sa.sa_flags = 0;
/* Register the handler for SIGINT. */
sa.sa_handler = SIGINT_handler;
sigaction (SIGINT, &sa, 0);
/* Register the handler for SIGQUIT. */
sa.sa_handler = SIGQUIT_handler;
sigaction (SIGQUIT, &sa, 0);
/* Run the main event loop. */
while (graceful_quit == 0
&& abortive_quit == 0)
do_work ();
if (abortive_quit == 1) {
_exit (1);
}
else if graceful_quit {
clean_up ();
exit (0);
}
/* NOTREACHED */
}
2. 设计模式
1) singleton pattern
2) adapter pattern
3) hook method pattern
3. 代码实现
1) 定义回调接口 hook method pattern
class Event_Handler
{
public:
// Hook method for the signal hook method.
virtual int handle_signal (int signum) = 0;
// ... other hook methods for other types of
// events such as timers, I/O, and
// synchronization objects.
};
2). 将信号处理组件(signal handler)作为一个单件使用 singleton pattern
class Signal_Handler
{
public:
// Entry point.
static Signal_Handler *instance (void);
// Register an event handler
// and return a pointer to any existing
// that was previously registered to handle
Event_Handler *register_handler (int signum,
Event_Handler *eh);
// Remove the
// by setting the slot in the
// table to NULL.
int remove_handler (int signum);
private:
// Ensure we're a Singleton.
Signal_Handler (void);
// Singleton pointer.
static Signal_Handler *instance_;
// Entry point adapter installed into
// (must be a static method or a stand-alone
// extern "C" function).
static void dispatcher (int signum);
// Table of pointers to concrete
// registered by applications. NSIG is the number of
// signals defined in .
static Event_Handler *signal_handlers_[NSIG];
};
3) 将dispatcher适配成系统注册回调的接口,通过它进行信号到事件的派发。
void Signal_Handler::dispatcher (int signum)
{
// Perform a sanity check...
if (Signal_handler::signal_handlers_[signum] != 0)
// Dispatch the handler's hook method.
Signal_handler::signal_handlers_
[signum]->handle_signal (signum);
}