own implementation of singleton and logger
This commit is contained in:
1 parent
f6c5bcca39
commit
6aed7b0027
19 files changed
+745
-206
No files matched your search
@@ -0,0 +1,49 @@
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include <thread>
|
||||
#include <csignal>
|
||||
class SignalShutdown {
|
||||
public:
|
||||
explicit SignalShutdown(std::function<void()> onShutdown)
|
||||
: m_OnShutdown(std::move(onShutdown))
|
||||
{
|
||||
// Block signals in this thread (and thus in subsequently created threads)
|
||||
sigset_t set;
|
||||
sigemptyset(&set);
|
||||
sigaddset(&set, SIGINT);
|
||||
sigaddset(&set, SIGTERM);
|
||||
sigaddset(&set, SIGHUP);
|
||||
sigaddset(&set, SIGQUIT);
|
||||
pthread_sigmask(SIG_BLOCK, &set, nullptr);
|
||||
|
||||
m_Thread = std::jthread([this, set]() mutable {
|
||||
while (m_Running) {
|
||||
int sig = 0;
|
||||
if (sigwait(&set, &sig) == 0) {
|
||||
if (!m_Running) break;
|
||||
if (m_OnShutdown) m_OnShutdown();
|
||||
// After requesting shutdown once, allow main to exit
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
~SignalShutdown() {
|
||||
m_Running = false;
|
||||
// Send a signal to unblock sigwait if desired; easiest is detach-safe join
|
||||
if (m_Thread.joinable()) {
|
||||
// If main exits without signals, thread may still be blocked in sigwait.
|
||||
// In that case, process teardown ends it anyway; but we prefer not to hang.
|
||||
// So we simply detach.
|
||||
m_Thread.detach();
|
||||
}
|
||||
}
|
||||
|
||||
SignalShutdown(const SignalShutdown&) = delete;
|
||||
SignalShutdown& operator=(const SignalShutdown&) = delete;
|
||||
|
||||
private:
|
||||
std::function<void()> m_OnShutdown;
|
||||
std::jthread m_Thread;
|
||||
bool m_Running = true;
|
||||
};
|
||||
Reference in new issue
Block a user