own implementation of singleton and logger

This commit is contained in:
faumaray committed 2026-01-19 15:36:21 +03:00
1 parent f6c5bcca39
commit 6aed7b0027
19 files changed
+745 -206

No files matched your search

+321
View File
@@ -0,0 +1,321 @@
#pragma once
#include <iostream>
#include <fstream>
#include <filesystem>
#include <format>
#include <print>
#include <chrono>
#include <source_location>
#include <mutex>
#include <thread>
#include <string>
#include <deque>
#include <condition_variable>
#include <atomic>
#include <unordered_map>
#include <ts6bot/Config.hpp>
#include "Singleton.hpp"
class Logger : public Singleton<Logger> {
friend class Singleton<Logger>;
// ANSI Color codes
struct Colors {
static constexpr auto RESET = "\033[0m";
static constexpr auto TRACE = "\033[37m"; // White
static constexpr auto DEBUG = "\033[36m"; // Cyan
static constexpr auto INFO = "\033[32m"; // Green
static constexpr auto WARNING = "\033[33m"; // Yellow
static constexpr auto ERROR = "\033[31m"; // Red
static constexpr auto CRITICAL = "\033[1;31m"; // Bold Red
};
// Internal structure to hold log data in the queue
struct LogEntry {
std::chrono::system_clock::time_point timestamp;
std::thread::id threadId;
std::source_location sourceLoc;
ts6bot::LogLevel level;
std::string message; // Pre-formatted user message
};
public:
explicit Logger(const ts6bot::LogLevel logLevel = ts6bot::LogLevel::Info)
: m_minLevel(logLevel), m_exit(false)
{
// 1. Setup File Sinks (Synchronous init)
try {
namespace fs = std::filesystem;
const fs::path logDir = "logs";
if (!fs::exists(logDir)) fs::create_directories(logDir);
// Time for filename (UTC)
const auto now = std::chrono::system_clock::now();
auto now_utc = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), now};
std::string timestamp = std::format("{:%Y-%m-%d_%H-%M-%S}", now_utc);
// Open trace file (all logs)
std::string traceFilename = std::format("trace_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Trace].open(logDir / traceFilename, std::ios::out | std::ios::app);
// Open error file
std::string errorFilename = std::format("error_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Error].open(logDir / errorFilename, std::ios::out | std::ios::app);
// Open warning file
std::string warningFilename = std::format("warning_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Warning].open(logDir / warningFilename, std::ios::out | std::ios::app);
// Open critical file
std::string criticalFilename = std::format("critical_{}.log", timestamp);
m_logFiles[ts6bot::LogLevel::Critical].open(logDir / criticalFilename, std::ios::out | std::ios::app);
// Check if files opened successfully
for (const auto& [level, file] : m_logFiles) {
if (!file.is_open()) {
std::println(std::cerr, "Logger Error: Failed to open log file for level: {}", levelToString(level));
}
}
} catch (const std::exception& e) {
std::println(std::cerr, "Logger Initialization Error: {}", e.what());
}
// 2. Start Worker Thread
m_workerThread = std::jthread([this](const std::stop_token &st) {
this->workerLoop(st);
});
}
~Logger() override {
// Signal exit and wake up worker
m_exit = true;
m_cv.notify_one();
// m_workerThread destructor will wait for join automatically
// Close all log files
for (auto &file: m_logFiles | std::views::values) {
if (file.is_open()) {
file.close();
}
}
}
// --- Public Logging API ---
// Generic log function
template <typename... Args>
void log(const ts6bot::LogLevel level, const std::source_location& loc, std::format_string<Args...> fmt, Args&&... args) {
if (level < m_minLevel || level == ts6bot::LogLevel::None) return;
try {
// 1. Capture context immediately
// 3. Push to Queue
{
LogEntry entry{
.timestamp = std::chrono::system_clock::now(),
.threadId = std::this_thread::get_id(),
.sourceLoc = loc,
.level = level,
// 2. Format message immediately (capture by value) to avoid dangling references
.message = std::format(fmt, std::forward<Args>(args)...)
};
std::lock_guard lock(m_queueMutex);
m_logQueue.push_back(std::move(entry));
}
m_cv.notify_one();
} catch (const std::exception& e) {
// Fallback if formatting fails
std::println(std::cerr, "Logging Error: {}", e.what());
}
}
// Convenience Wrappers
template <typename... Args>
void trace(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Trace, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void info(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Info, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void error(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Error, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void warn(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Warning, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void debug(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Debug, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void critical(std::format_string<Args...> fmt, Args&&... args) {
log(ts6bot::LogLevel::Critical, std::source_location::current(), fmt, std::forward<Args>(args)...);
}
void SetLogLevel(const ts6bot::LogLevel level) { m_minLevel = level; }
private:
// --- Backend Worker ---
void workerLoop(std::stop_token st) {
while (!st.stop_requested() || !isQueueEmpty()) {
std::unique_lock lock(m_queueMutex);
// Wait until data is available or stop is requested
m_cv.wait(lock, [this, &st] {
return !m_logQueue.empty() || st.stop_requested() || m_exit;
});
if (m_logQueue.empty()) {
if (st.stop_requested() || m_exit) break;
continue;
}
// Swap queue to local buffer to minimize lock time
std::deque<LogEntry> localQueue;
std::swap(localQueue, m_logQueue);
lock.unlock();
// Process Batch
for (const auto& entry : localQueue) {
writeLog(entry);
}
}
}
bool isQueueEmpty() {
std::lock_guard lock(m_queueMutex);
return m_logQueue.empty();
}
void writeLog(const LogEntry& entry) {
// Format: "HH:MM:SS.nanoseconds [thread_id] /path/to/file.cpp:line LOG_LEVEL message"
auto utc_time = std::chrono::zoned_time{std::chrono::locate_zone("UTC"), entry.timestamp};
// Extract nanoseconds
const auto duration = entry.timestamp.time_since_epoch();
const auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration);
const auto nanoseconds = std::chrono::duration_cast<std::chrono::nanoseconds>(duration - seconds);
// Format source location
std::string sourceLocation = std::format("{}:{}",
entry.sourceLoc.file_name(),
entry.sourceLoc.line());
// Get thread ID as integer
std::ostringstream threadIdStream;
threadIdStream << entry.threadId;
std::string threadIdStr = threadIdStream.str();
// Construct log without colors (for file)
const std::string fileLog = std::format("{:%H:%M:%S}.{:09} [{}] {:<28} {:<9} {}\n",
utc_time,
nanoseconds.count(),
threadIdStr,
sourceLocation,
levelToString(entry.level),
entry.message
);
// Construct colored log (for console)
const char* color = getColorForLevel(entry.level);
std::string consoleLog = std::format("{}{:%H:%M:%S}.{:09}{} [{}] {:<28} {}{:<9}{} {}\n",
color,
utc_time,
nanoseconds.count(),
Colors::RESET,
threadIdStr,
sourceLocation,
color,
levelToString(entry.level),
Colors::RESET,
entry.message
);
// Print to Console with colors
std::print(std::cout, "{}", consoleLog);
// Write to trace file (all logs) - no colors
if (m_logFiles.at(ts6bot::LogLevel::Trace).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Trace) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Trace).flush();
}
// Write to specific level files - no colors
if (entry.level == ts6bot::LogLevel::Error && m_logFiles.at(ts6bot::LogLevel::Error).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Error) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Error).flush();
}
else if (entry.level == ts6bot::LogLevel::Warning && m_logFiles.at(ts6bot::LogLevel::Warning).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Warning) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Warning).flush();
}
else if (entry.level == ts6bot::LogLevel::Critical && m_logFiles.at(ts6bot::LogLevel::Critical).is_open()) {
m_logFiles.at(ts6bot::LogLevel::Critical) << fileLog;
m_logFiles.at(ts6bot::LogLevel::Critical).flush();
}
}
static const char* getColorForLevel(const ts6bot::LogLevel level) {
switch (level) {
case ts6bot::LogLevel::Trace: return Colors::TRACE;
case ts6bot::LogLevel::Debug: return Colors::DEBUG;
case ts6bot::LogLevel::Info: return Colors::INFO;
case ts6bot::LogLevel::Warning: return Colors::WARNING;
case ts6bot::LogLevel::Error: return Colors::ERROR;
case ts6bot::LogLevel::Critical: return Colors::CRITICAL;
default: return Colors::RESET;
}
}
static std::string_view levelToString(const ts6bot::LogLevel level) {
switch (level) {
case ts6bot::LogLevel::Trace: return "TRACE";
case ts6bot::LogLevel::Debug: return "DEBUG";
case ts6bot::LogLevel::Info: return "INFO";
case ts6bot::LogLevel::Warning: return "WARNING";
case ts6bot::LogLevel::Error: return "ERROR";
case ts6bot::LogLevel::Critical: return "CRITICAL";
default: return "UNKNOWN";
}
}
private:
ts6bot::LogLevel m_minLevel;
std::unordered_map<ts6bot::LogLevel, std::ofstream> m_logFiles;
// Concurrency
std::deque<LogEntry> m_logQueue;
std::mutex m_queueMutex;
std::condition_variable m_cv;
std::jthread m_workerThread;
std::atomic<bool> m_exit;
};
#define LOG_IF_ALIVE(level, fmt, ...) \
do { \
if (Logger::isAlive()) { \
Logger::getInstance()->log(level, std::source_location::current(), fmt __VA_OPT__(,) __VA_ARGS__); \
} \
} while (0)
// --- Public API Macros ---
#define LOG_TRACE(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Trace, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_DEBUG(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Debug, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_INFO(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Info, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_WARN(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Warning, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_ERROR(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Error, fmt __VA_OPT__(,) __VA_ARGS__)
#define LOG_CRITICAL(fmt, ...) LOG_IF_ALIVE(ts6bot::LogLevel::Critical, fmt __VA_OPT__(,) __VA_ARGS__)
+3 -10
View File
@@ -3,16 +3,8 @@
// #include "Youtube/Client.hpp"
#include "ts6bot/AudioDecoder.hpp"
#include <memory>
#include <quill/Backend.h>
#include <quill/Frontend.h>
#include <quill/LogMacros.h>
#include <quill/Logger.h>
#include <quill/core/SinkManager.h>
#include <singleton_atomic.hpp>
#include "ts6bot/Config.hpp"
#include <ts6bot/MusicManager.hpp>
#include "quill/sinks/FileSink.h"
#include "quill/sinks/ConsoleSink.h"
#include <ts6bot/Proxy.hpp>
#include "PluginDefinitions.hpp"
@@ -20,7 +12,6 @@
class EchoionCore : public IEchoionPlugin {
// Dependencies
quill::Logger *m_logger = nullptr;
std::shared_ptr<TS3Functions> m_ts3;
std::unique_ptr<MusicManager> m_musicManager;
@@ -415,5 +406,7 @@ extern "C" {
return new EchoionCore(std::make_shared<TS3Functions>(*funcs));
}
void DestroyPlugin(const IEchoionPlugin *plugin) { delete plugin; }
void DestroyPlugin(const IEchoionPlugin *plugin) {
delete plugin;
}
}
+6 -3
View File
@@ -26,13 +26,15 @@ namespace definitions {
struct QueueItem {
std::string name;
std::string videoId;
std::string shortUrl;
std::string length;
std::string requester;
std::optional<Streams> streams;
QueueItem() = default;
QueueItem(std::string name, std::string videoId, std::string requested_by, const std::optional<Streams> & streams)
: name{std::move(name)}, videoId(std::move(videoId)), requester{std::move(requested_by)}, streams{streams} {}
QueueItem(std::string name, std::string videoId,std::string shortUrl,std::string length, std::string requested_by, const std::optional<Streams> & streams)
: name{std::move(name)}, videoId(std::move(videoId)),shortUrl(std::move(shortUrl)), length(std::move(length)), requester{std::move(requested_by)}, streams{streams} {}
};
@@ -43,6 +45,7 @@ namespace definitions {
std::string thumbnail;
std::string viewCount;
std::string url;
std::string shortUrl;
std::string videoId;
};
@@ -71,6 +74,6 @@ template <> struct glz::meta<definitions::Streams> {
template <> struct glz::meta<definitions::QueueItem> {
using T = definitions::QueueItem;
static constexpr auto value =
object("name", &T::name, "videoId", &T::videoId, "requester", &T::requester,
object("name", &T::name, "videoId", &T::videoId, "shortUrl", &T::shortUrl, "length", &T::length, "requester", &T::requester,
"streams", &T::streams);
};
+77
View File
@@ -0,0 +1,77 @@
#pragma once
#include <memory>
#include <mutex>
#include <concepts>
#include <utility>
/**
* @brief C++26 Smart Singleton for DLL Hot-Reloading.
* Uses shared_ptr to ensure memory safety across thread boundaries
* during forceful destruction and DLL unloads.
*/
template <typename T>
class Singleton {
private:
// This "Token" trick allows std::shared_ptr to create the object
// even if T's constructor is private/protected.
struct ConstructorProxy : public T {
template<typename... Args>
ConstructorProxy(Args&&... args) : T(std::forward<Args>(args)...) {}
};
public:
// Delete copy/move
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
template <typename... Args>
static std::shared_ptr<T> init(Args&&... args) {
auto ptr = m_instance.load(std::memory_order_acquire);
if (ptr) return ptr;
std::lock_guard lock(m_lifecycle_mutex);
ptr = m_instance.load(std::memory_order_relaxed);
if (!ptr) {
// We wrap T in ConstructorProxy so 'new' works here,
// but the resulting shared_ptr is still shared_ptr<T>.
ptr = std::make_shared<ConstructorProxy>(std::forward<Args>(args)...);
m_instance.store(ptr, std::memory_order_release);
}
return ptr;
}
/**
* @brief Access the existing instance.
* @throws std::runtime_error if init() hasn't been called yet.
*/
static std::shared_ptr<T> getInstance() {
auto ptr = m_instance.load(std::memory_order_acquire);
if (!ptr) {
throw std::runtime_error("Singleton accessed via get() before init()!");
}
return ptr;
}
/**
* @brief Safe destruction for DLL unloading.
* Shared_ptr ensures that threads currently using the instance
* don't crash; the memory is freed only when the last reference drops.
*/
static void destroyInstance() {
std::lock_guard lock(m_lifecycle_mutex);
m_instance.store(nullptr, std::memory_order_release);
}
static bool isAlive() {
return m_instance.load(std::memory_order_acquire) != nullptr;
}
protected:
Singleton() = default;
virtual ~Singleton() = default;
private:
// atomic<shared_ptr> is a C++20 feature, perfect for C++26
static inline std::atomic<std::shared_ptr<T>> m_instance{nullptr};
static inline std::mutex m_lifecycle_mutex;
};
+30
View File
@@ -0,0 +1,30 @@
#include <vector>
#include <functional>
#include <algorithm>
#include <mutex>
class SingletonManager {
public:
// Priority: Higher numbers are destroyed LAST (e.g., Logger = 100)
static void registerShutdown(const int priority, const std::function<void()> &shutdownFunc) {
m_registry.push_back({priority, shutdownFunc});
// Sort so that high priority stays at the end (destroyed last)
std::ranges::sort(m_registry, [](const auto& a, const auto& b) {
return a.priority < b.priority;
});
}
static void shutdownAll() {
// Destroy in reverse priority (highest priority first? No, usually reverse order of arrival)
// Here we destroy from lowest priority to highest.
for (auto& [priority, func] : m_registry) {
std::cerr << priority << ": " << &func << std::endl;
func();
}
m_registry.clear();
}
private:
struct Entry { int priority; std::function<void()> func; };
static inline std::vector<Entry> m_registry;
};
+32 -3
View File
@@ -15,7 +15,7 @@
#include <quickjs.h>
// Project (Assuming similar structure to your Spotify bot)
#include <ts6bot/Proxy.hpp>
#include <Logger.hpp>
#include <PluginDefinitions.hpp>
namespace YouTube {
@@ -40,6 +40,23 @@ struct Snippet {
std::string liveBroadcastContent;
std::string publishTime;
};
struct PlayListResourceId {
std::string kind;
std::string videoId;
};
struct PlayListSnippet{
std::string publishedAt;
std::string channelId;
std::string title;
std::string description;
std::map<std::string, Thumbnail> thumbnails;
std::string channelTitle;
std::string playlistId;
int position;
PlayListResourceId resourceId;
std::string videoOwnerChannelTitle;
std::string videoOwnerChannelId;
};
struct ResourceId {
std::string kind;
@@ -84,6 +101,13 @@ struct SearchResult {
Snippet snippet;
};
struct SearchPlaylistResult {
std::string kind;
std::string etag;
std::string id;
PlayListSnippet snippet;
};
// API Response Wrappers
template <typename T> struct PageResult {
std::string kind;
@@ -151,7 +175,9 @@ struct SearchParams {
std::string videoDuration = "any"; // any, long, medium, short
bool rawQuery = false; // Set to true to preserve -, |, etc. in query
};
struct ShortenResponse {
std::string shortUrl;
};
// ============================================================================
// Main YouTube Client
// ============================================================================
@@ -178,6 +204,8 @@ public:
void SetAccessToken(std::string token) { m_AccessToken = std::move(token); }
void SetApiKey(std::string key) { m_ApiKey = std::move(key); }
auto ShortUrl(const std::string& url) const -> Result<std::string>;
// ========================================================================
// Search API
// ========================================================================
@@ -214,8 +242,9 @@ public:
// https://developers.google.com/youtube/v3/docs/playlistItems/list
auto GetPlaylistItems(const std::string &playlistId,
const std::string &pageToken = "")
-> Result<PageResult<SearchResult>>; // Reusing SearchResult as structure
-> Result<PageResult<SearchPlaylistResult>>; // Reusing SearchResult as structure
// is similar enough for snippet
auto GetPlaylistVideos(const std::string& playlistId) -> Result<std::vector<Video>>;
// ========================================================================
// Player API (The "Extraction" Logic)
// ========================================================================
+2 -4
View File
@@ -8,6 +8,8 @@
#include <thread>
#include <vector>
#include "Logger.hpp"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
@@ -37,10 +39,6 @@ public:
bool IsFinished() const { return m_finished.load(); }
private:
void Log(const std::string &msg) {
std::lock_guard<std::mutex> lock(m_logMtx);
std::cout << "[AudioDecoder] " << msg << std::endl;
}
void Cleanup();
void InternalDecode(std::string url, int targetSampleRate);
std::atomic<DecodeStatus> m_status{DecodeStatus::Idle};
+13 -3
View File
@@ -1,15 +1,24 @@
#pragma once
#include <cstdint>
#include <iostream>
#include <singleton_atomic.hpp>
#include <string>
#include <ts6bot/Proxy.hpp>
#include <glaze/glaze.hpp>
#include "Singleton.hpp"
namespace ts6bot {
enum class LogLevel { Critical, Error, Warning, Info, Trace };
enum class LogLevel {
Trace,
Debug,
Info,
Warning,
Error,
Critical,
None
};
struct ServerQueryConfig {
std::string host{"127.0.0.1"};
@@ -48,7 +57,8 @@ struct Config {
ProxyConfiguration proxy{};
};
class Configuration : public SingletonAtomic<Configuration> {
class Configuration : public Singleton<Configuration> {
friend class Singleton<Configuration>;
public:
const Config getConfig() const noexcept { return m_config; }
-22
View File
@@ -1,22 +0,0 @@
#pragma once
#include <string_view>
#include "quill/Backend.h"
#include "quill/Frontend.h"
#include "quill/LogMacros.h"
#include "quill/Logger.h"
#include "quill/sinks/FileSink.h"
#include "quill/sinks/ConsoleSink.h"
namespace ts6bot {
class Log {
public:
static void init(std::string_view file_path);
static quill::Logger* logger();
private:
static quill::Logger* g_logger;
};
} // namespace ts6bot
+7 -7
View File
@@ -10,22 +10,21 @@
#include <mutex>
#include <queue>
#include <set>
#include <singleton_atomic.hpp>
#include <string>
#include <teamspeak/public_definitions.h>
#include <thread>
#include <ts3_functions.h>
#include <ts6bot/AudioDecoder.hpp>
#include <quill/Logger.h>
#include <quill/LogMacros.h>
#include <vector>
class MusicManager {
public:
explicit MusicManager(std::shared_ptr<TS3Functions> functions, quill::Logger* logger, std::uint64_t serverConnectionHandlerID = 0);
explicit MusicManager(std::shared_ptr<TS3Functions> functions, std::uint64_t serverConnectionHandlerID = 0);
~MusicManager();
struct Music {
std::string name;
std::string shortUrl;
std::string length;
std::string videoId;
std::string requestedBy;
YouTube::Result<definitions::Streams> streams;
@@ -54,13 +53,15 @@ public:
std::optional<Music> getCurrent() const { return m_current; }
void removeFromQueue(std::size_t index);
void removeFromQueue(const std::string &name);
void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& req, std::optional<definitions::Streams> streams);
void addToQueueDirect(const std::string& vid, const std::string& title, const std::string& shortUrl, const std::string& length, const std::string& req, std::optional<definitions::Streams> streams);
void checkQueueAndPlay();
// Youtube / Search
std::vector<definitions::SearchResultItem> search(std::string name, int maxResults = 5) const;
void playUrl(std::string url, const std::string &requester = "");
void playPlaylist(const std::string& playlistId, const std::string& requester);
// Helper to extract playlist ID from URL
std::optional<std::string> extractPlaylistId(std::string_view url);
// Selection Logic
// Stores the results for a specific user to select later
void storePendingSearch(anyID clientId,
@@ -72,7 +73,6 @@ private:
static std::string formatDuration(const std::string &isoDuration);
void updateWhisperList();
quill::Logger* m_logger;
std::shared_ptr<TS3Functions> m_functions{nullptr};
std::unique_ptr<AudioDecoder> m_microphone{nullptr};
std::unique_ptr<YouTube::Client> m_client{nullptr};
-17
View File
@@ -1,17 +0,0 @@
#pragma once
#include <functional>
#include <thread>
class SignalShutdown {
public:
explicit SignalShutdown(std::function<void()> onShutdown);
~SignalShutdown();
SignalShutdown(const SignalShutdown&) = delete;
SignalShutdown& operator=(const SignalShutdown&) = delete;
private:
std::function<void()> m_OnShutdown;
std::thread m_Thread;
bool m_Running = true;
};
+49
View File
@@ -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;
};