Scarab  v2.4.4
Project 8 C++ Utility Library
signal_handler.cc
Go to the documentation of this file.
1 /*
2  * signal_handler.cc
3  *
4  * Created on: Dec 3, 2013
5  * Author: N.S. Oblath
6  */
7 
8 #include "signal_handler.hh"
9 
10 #include "cancelable.hh"
11 #include "error.hh"
12 #include "logger.hh"
13 
14 #include <signal.h>
15 #include <thread>
16 
17 namespace scarab
18 {
19  LOGGER( slog, "signal_handler" );
20 
22 
25 
26  std::mutex signal_handler::f_mutex;
28 
30  {
31  if( ! f_handling_sig_int && signal( SIGINT, signal_handler::handler_cancel_threads ) == SIG_ERR )
32  {
33  throw error() << "Unable to handle SIGINT\n";
34  }
35  else
36  {
37  f_handling_sig_int = true;
38  }
39 
40 #ifndef _WIN32
41  if( ! f_handling_sig_quit && signal( SIGQUIT, signal_handler::handler_cancel_threads ) == SIG_ERR )
42  {
43  throw error() << "Unable to handle SIGQUIT\n";
44  }
45  else
46  {
47  f_handling_sig_quit = true;
48  }
49 
50  if( signal(SIGPIPE, SIG_IGN) == SIG_ERR )
51  {
52  throw error() << "Unable to ignore SIGPIPE\n";
53  }
54 #endif
55  }
56 
58  {
59  }
60 
62  {
63  f_mutex.lock();
64  f_cancelers.insert( a_cancelable );
65  f_mutex.unlock();
66  return;
67  }
68 
70  {
71  f_mutex.lock();
72  f_cancelers.erase( a_cancelable );
73  f_mutex.unlock();
74  return;
75  }
76 
78  {
79  f_mutex.lock();
80  f_got_exit_signal = false;
81  f_handling_sig_int = false;
82  f_handling_sig_quit = false;
83  f_cancelers.clear();
84  f_mutex.unlock();
85  return;
86  }
87 
89  {
90  return f_got_exit_signal;
91  }
92 
94  {
95  print_message();
96 
97  f_mutex.lock();
98  f_got_exit_signal = true;
99  while( ! f_cancelers.empty() )
100  {
101  (*f_cancelers.begin())->cancel();
102  f_cancelers.erase( f_cancelers.begin() );
103  std::this_thread::sleep_for( std::chrono::seconds(1) );
104  }
105  f_mutex.unlock();
106 
107 #ifdef _WIN32
108  ExitProcess( 1 );
109 #endif
110  return;
111  }
112 
114  {
115  LPROG( slog, "\n\nHello! Your signal is being handled by signal_handler.\n"
116  << "Have a nice day!\n" );
117  return;
118  }
119 
120 } /* namespace scarab */
static bool f_handling_sig_int
LOGGER(mtlog, "authentication")
#define LPROG(...)
Definition: logger.hh:363
static bool f_got_exit_signal
Contains the logger class and macros, based on Kasper&#39;s KLogger class.
static std::mutex f_mutex
static void print_message()
static bool got_exit_signal()
static void handler_cancel_threads(int _ignored)
static bool f_handling_sig_quit
static cancelers f_cancelers
void add_cancelable(cancelable *a_cancelable)
void remove_cancelable(cancelable *a_cancelable)
std::set< cancelable *> cancelers