From 3920485900a86011eed2b04c8627e78705a47ee7 Mon Sep 17 00:00:00 2001 From: arkadiusz Date: Fri, 26 Jul 2024 10:22:16 +0200 Subject: [PATCH] Add signal handling for orderly shutdown - Add 'signalHandler' function to handle SIGINT for graceful shutdown - Update 'consoleHandler' and WebSocket handler loop to check for a 'running' atomic flag - Signal processing in 'main.cpp' to intercept SIGINT and set the 'running' flag to false - Add '' and '' headers for signal handling and atomic operations These changes ensure that the application can be terminated properly when interrupted by SIGINT (Ctrl+C). --- src/handler.cpp | 12 ++++++++++-- src/handler.hpp | 3 +++ src/main.cpp | 6 +++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/handler.cpp b/src/handler.cpp index 1ac22e70..ae7b3a0c 100644 --- a/src/handler.cpp +++ b/src/handler.cpp @@ -1,6 +1,7 @@ #include "handler.hpp" #include #include +#include // A list of colors const std::array, 7> predefinedColors = {{ @@ -35,7 +36,7 @@ void initDevices() { void consoleHandler(bool &flagPaused, std::set& selected_serials) { std::string input; - while (true) { + while (running) { std::cout << "Enter command: "; std::getline(std::cin, input); if (input == "Search") { @@ -90,4 +91,11 @@ void consoleHandler(bool &flagPaused, std::set& selected_serials) { } } } -} +} + +void signalHandler(int signal) { + if (signal == SIGINT) { + std::cout << "\nSIGINT received, shutting down gracefully...\n"; + running = false; + } +} diff --git a/src/handler.hpp b/src/handler.hpp index df5870eb..8e463997 100644 --- a/src/handler.hpp +++ b/src/handler.hpp @@ -5,6 +5,7 @@ #include #include #include +#include // global variables inline OmniscopeDeviceManager deviceManager{}; @@ -12,8 +13,10 @@ inline std::vector> devices; inline std::map> colorMap; inline std::optional sampler{}; inline std::map>> captureData; +inline std::atomic running{true}; void initDevices(); void consoleHandler(bool &flagPaused, std::set& selected_serials); +void signalHandler(int signal); #endif diff --git a/src/main.cpp b/src/main.cpp index fa4d1539..2d150429 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -2,6 +2,7 @@ #include "handler.hpp" #include #include +#include int main(int argc, char** argv) { @@ -17,12 +18,15 @@ int main(int argc, char** argv) { WebSocketHandler wsHandler(wsURI); + // Signal handler for SIGINT + std::signal(SIGINT, signalHandler); + // Start console handler thread std::thread consoleThread(consoleHandler, std::ref(flagPaused), std::ref(selected_serials)); // WebSocket handler thread std::thread webSocketThread([&]() { - while (true) { + while (running) { if (sampler.has_value() && !flagPaused) { sampler->copyOut(captureData); wsHandler.send(captureData, selected_serials);