Skip to content
This repository was archived by the owner on Jul 21, 2023. It is now read-only.

Commit 2e364a5

Browse files
committed
EventSignal 🐟
1 parent 699776b commit 2e364a5

File tree

1 file changed

+24
-19
lines changed

1 file changed

+24
-19
lines changed

include/marko/utils.hpp

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
#pragma once
22

33
#include <atomic>
4+
#include <exception>
5+
#include <signal.h>
46

57
// https://gist.github.com/jncornett/e449826d2a1bd6b481f818176be0d2de
68
// https://stackoverflow.com/questions/69385119/how-do-wait-and-notify-work-for-stdatomic-in-c20
@@ -20,9 +22,6 @@ class Event {
2022
};
2123

2224

23-
24-
#include <signal.h>
25-
2625
/*
2726
https://stackoverflow.com/questions/1641182/how-can-i-catch-a-ctrl-c-event
2827
https://www.geeksforgeeks.org/inheritance-in-c/
@@ -41,32 +40,38 @@ kevin@Logan build $ kill -l
4140
29) SIGINFO 30) SIGUSR1 31) SIGUSR2
4241
*/
4342

44-
/*
45-
This class captures the SIGINT signal and sets ok to false. Since ok is
46-
static, any class that inherits this will see the status change and
47-
allow it close down cleanly.
43+
/**
44+
* Captures a signal and calls a callback function.
45+
*
46+
* ref: https://man7.org/linux/man-pages/man2/sigaction.2.html
4847
*/
49-
class SigCapture {
48+
class SignalFunc {
5049
public:
51-
SigCapture(): enabled(false) {}
52-
static void my_handler(int s) { ok = false; }
53-
void on(){
50+
SignalFunc() {}
51+
void enable(void(*f)(int), int signum=SIGINT) {
5452
if (enabled) return;
5553

54+
if (signum == SIGKILL || signum == SIGKILL) {
55+
throw std::invalid_argument("** Cannot capture signals SIGKILL or SIGSTOP");
56+
}
57+
5658
struct sigaction sigIntHandler;
57-
sigIntHandler.sa_handler = SigCapture::my_handler;
59+
sigIntHandler.sa_handler = f;
5860
sigemptyset(&sigIntHandler.sa_mask);
5961
sigIntHandler.sa_flags = 0;
6062

61-
sigaction(SIGINT, &sigIntHandler, NULL);
63+
sigaction(signum, &sigIntHandler, NULL);
6264

6365
enabled = true;
6466
}
65-
void shutdown() { ok = false; }
66-
67-
// protected:
68-
static bool ok; // global status on if a SIGINT has occured
69-
bool enabled;
67+
protected:
68+
bool enabled{false};
7069
};
7170

72-
bool SigCapture::ok = true;
71+
/**
72+
* Combination of the Event and SignalFunc classes.
73+
*/
74+
class EventSignal: public Event, public SignalFunc {
75+
public:
76+
EventSignal() {}
77+
};

0 commit comments

Comments
 (0)