Scarab  v2.4.7
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 #define SCARAB_API_EXPORTS
9 
10 #include "signal_handler.hh"
11 
12 #include "cancelable.hh"
13 #include "error.hh"
14 #include "logger.hh"
15 
16 #include <signal.h>
17 #include <thread>
18 
19 #ifdef _WIN32
20 #include <Windows.h>
21 //#include "processthreadsapi.h"
22 #endif
23 
24 namespace scarab
25 {
26  LOGGER( slog, "signal_handler" );
27 
29 
32 
33  std::mutex signal_handler::f_mutex;
35 
37  {
38  if( ! f_handling_sig_int && signal( SIGINT, signal_handler::handler_cancel_threads ) == SIG_ERR )
39  {
40  throw error() << "Unable to handle SIGINT\n";
41  }
42  else
43  {
44  f_handling_sig_int = true;
45  }
46 
47 #ifndef _WIN32
48  if( ! f_handling_sig_quit && signal( SIGQUIT, signal_handler::handler_cancel_threads ) == SIG_ERR )
49  {
50  throw error() << "Unable to handle SIGQUIT\n";
51  }
52  else
53  {
54  f_handling_sig_quit = true;
55  }
56 
57  if( signal(SIGPIPE, SIG_IGN) == SIG_ERR )
58  {
59  throw error() << "Unable to ignore SIGPIPE\n";
60  }
61 #endif
62  }
63 
65  {
66  }
67 
69  {
70  f_mutex.lock();
71  f_cancelers.insert( a_cancelable );
72  f_mutex.unlock();
73  return;
74  }
75 
77  {
78  f_mutex.lock();
79  f_cancelers.erase( a_cancelable );
80  f_mutex.unlock();
81  return;
82  }
83 
85  {
86  f_mutex.lock();
87  f_got_exit_signal = false;
88  f_handling_sig_int = false;
89  f_handling_sig_quit = false;
90  f_cancelers.clear();
91  f_mutex.unlock();
92  return;
93  }
94 
96  {
97  return f_got_exit_signal;
98  }
99 
101  {
102  print_message();
103 
104  f_mutex.lock();
105  f_got_exit_signal = true;
106  while( ! f_cancelers.empty() )
107  {
108  (*f_cancelers.begin())->cancel();
109  f_cancelers.erase( f_cancelers.begin() );
110  std::this_thread::sleep_for( std::chrono::seconds(1) );
111  }
112  f_mutex.unlock();
113 
114 #ifdef _WIN32
115  ExitProcess( 1 );
116 #endif
117  return;
118  }
119 
121  {
122  LPROG( slog, "\n\nHello! Your signal is being handled by signal_handler.\n"
123  << "Have a nice day!\n" );
124  return;
125  }
126 
127 } /* namespace scarab */
static bool f_handling_sig_int
LOGGER(mtlog, "authentication")
#define LPROG(...)
Definition: logger.hh:368
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