arduino-emulator
Loading...
Searching...
No Matches
SignalHandler.h
1/*
2 SignalHandler.h
3 Copyright (c) 2025 Phil Schatzmann. All right reserved.
4
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18*/
19
20#pragma once
21#include <signal.h>
22#include <csignal>
23#include <functional>
24#include <vector>
25#include <map>
26#include <algorithm>
27
28#undef INADDR_NONE
29
30// Generic signal handler utility
32 public:
33 using HandlerFunc = std::function<void(int)>;
34
35 static void registerHandler(int signum, HandlerFunc handler) {
36 auto& vec = getHandlers()[signum];
37 vec.push_back(handler);
38 std::signal(signum, SignalHandler::dispatch);
39 }
40
41 private:
42 static std::map<int, std::vector<HandlerFunc>>& getHandlers() {
43 static std::map<int, std::vector<HandlerFunc>> handlers;
44 return handlers;
45 }
46 static void dispatch(int signum) {
47 auto& handlers = getHandlers();
48 auto it = handlers.find(signum);
49 if (it != handlers.end()) {
50 for (auto& func : it->second) {
51 func(signum);
52 }
53 }
54 exit(0);
55 }
56};
Definition SignalHandler.h:31