Files
Echoion/include/Shared/SignalShutdown.hpp
T

50 lines
1.6 KiB
C++

#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;
};