Utopia  2
Framework for studying models of complex & adaptive systems.
signal.hh
Go to the documentation of this file.
1 #ifndef UTOPIA_CORE_SIGNAL_HH
2 #define UTOPIA_CORE_SIGNAL_HH
3 
4 #include <csignal>
5 #include <atomic>
6 
7 namespace Utopia {
8 
10 
15 std::atomic<bool> stop_now;
16 
18 std::atomic<int> received_signum;
19 
21 void default_signal_handler(int signum) {
22  stop_now.store(true);
23  received_signum.store(signum);
24 }
25 
27 
34 template<typename Handler>
35 void attach_signal_handler(int signum, Handler&& handler) {
36  // Initialize the signal flag to make sure it is false
37  stop_now.store(false);
38 
39  // Also initialize the global variable storing the received signal
40  received_signum.store(0);
41 
42  // Use POSIX-style sigaction definition rather than deprecated signal
43  struct sigaction sa;
44  sa.sa_handler = handler;
45  sa.sa_flags = 0;
46 
47  // Add only the given signal to the set of actions
48  // See sigaddset documentation: https://linux.die.net/man/3/sigfillset
49  sigaddset(&sa.sa_mask, signum);
50 
51  sigaction(signum, &sa, NULL);
52 }
53 
55 void attach_signal_handler(int signum) {
57 }
58 
59 } // namespace Utopia
60 
61 #endif // UTOPIA_CORE_SIGNAL_HH
Definition: agent.hh:11
std::atomic< bool > stop_now
The flag indicating whether to stop whatever is being done right now.
Definition: signal.hh:15
void default_signal_handler(int signum)
Default signal handler function, only setting the stop_now global flag.
Definition: signal.hh:21
std::atomic< int > received_signum
The received signal value.
Definition: signal.hh:18
void attach_signal_handler(int signum, Handler &&handler)
Attaches a signal handler for the given signal via sigaction.
Definition: signal.hh:35