/***************************************************************************
		System signal Class ( signal_handle.cpp )
			-----------------------------------------

	begin      : 2015/03/18
	copyright  : (C) 2013 Solbox Inc.
	author     : Development 1 Team
					- 2015/03/19 - 1st dadamin
	email      : storage.sd@solbox.com
	version    : 3.5.0

CopyRight(C) 2005 Solbox Inc. All Rights reserved.
Redistribution and use in source and binary forms, with or with out
modification, are not permitted in outside of Solbox Inc.
***************************************************************************/

#include <cstddef>
#include <string.h>
#include "Signal_handle.h"

Signal_Handler *Signal_Handler::instance_ = NULL;
Event_Handler *Signal_Handler::signal_handlers_[NSIG];

Signal_Handler::Signal_Handler()
{

}

Signal_Handler::~Signal_Handler()
{

}

Signal_Handler* Signal_Handler::instance()
{
	if(!Signal_Handler::instance_)
		Signal_Handler::instance_ = new Signal_Handler();
	return Signal_Handler::instance_;
}

Event_Handler * Signal_Handler::register_handler(int signum,
								Event_Handler *eh)
{
	// Copy the <old_eh> from the <signum> slot in 
	// the <signal_handlers_> table.
	Event_Handler *old_eh =
		Signal_Handler::signal_handlers_[signum];

	// Store <eh> into the <signum> slot in the
	// <signal_handlers_> table.
	Signal_Handler::signal_handlers_[signum] = eh;

	// Register the <dispatcher> to handle this
	// <signum>.
	struct sigaction sa;
	sa.sa_handler = Signal_Handler::dispatcher;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sigaction(signum, &sa, 0);

	return old_eh;
}

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);
}

int Signal_Handler::remove_handler(int signum)
{
	Signal_Handler::signal_handlers_[signum] = 0;
	return 0;
}

int Signal_Handler::register_ignore(int signum)
{
	struct sigaction sa;

	sa.sa_handler = SIG_IGN;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	int retval = sigaction(signum, &sa, 0);


	return retval;
}
