diff --git a/src/app/sdl3_app.hpp b/src/app/sdl3_app.hpp index 5dc2b7a..1f38126 100644 --- a/src/app/sdl3_app.hpp +++ b/src/app/sdl3_app.hpp @@ -59,6 +59,7 @@ class Sdl3App { public: explicit Sdl3App(const std::filesystem::path& scriptPath, bool luaDebug = false); void Run(); + static bool ShouldStop(); private: struct RenderObject { diff --git a/src/app/sdl3_app_core.cpp b/src/app/sdl3_app_core.cpp index 9da54db..329ad98 100644 --- a/src/app/sdl3_app_core.cpp +++ b/src/app/sdl3_app_core.cpp @@ -2,7 +2,9 @@ #include "app/sdl3_app.hpp" #include "app/trace.hpp" +#include #include +#include #include #include #include @@ -14,6 +16,8 @@ namespace sdl3cpp::app { +extern std::atomic g_signalReceived; + std::vector ReadFile(const std::string& path) { TRACE_FUNCTION(); @@ -116,6 +120,10 @@ Sdl3App::Sdl3App(const std::filesystem::path& scriptPath, bool luaDebug) TRACE_VAR(scriptPath); } +bool Sdl3App::ShouldStop() { + return g_signalReceived.load(); +} + void Sdl3App::Run() { TRACE_FUNCTION(); InitSDL(); @@ -219,6 +227,10 @@ void Sdl3App::MainLoop() { bool running = true; auto start = std::chrono::steady_clock::now(); while (running) { + if (ShouldStop()) { + running = false; + break; + } SDL_Event event; while (SDL_PollEvent(&event)) { if (event.type == SDL_EVENT_QUIT) { diff --git a/src/main.cpp b/src/main.cpp index 2ee6336..fba7eed 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -5,6 +5,8 @@ #include #include +#include +#include #include #include #include @@ -20,8 +22,23 @@ #include "app/sdl3_app.hpp" #include +namespace sdl3cpp::app { +std::atomic g_signalReceived{false}; +} + namespace { +void SignalHandler(int signal) { + if (signal == SIGINT || signal == SIGTERM) { + sdl3cpp::app::g_signalReceived.store(true); + } +} + +void SetupSignalHandlers() { + std::signal(SIGINT, SignalHandler); + std::signal(SIGTERM, SignalHandler); +} + std::filesystem::path FindScriptPath(const char* argv0) { std::filesystem::path executable; if (argv0 && *argv0 != '\0') { @@ -294,6 +311,7 @@ void WriteRuntimeConfigJson(const RuntimeConfig& runtimeConfig, int main(int argc, char** argv) { SDL_SetMainReady(); + SetupSignalHandlers(); try { AppOptions options = ParseCommandLine(argc, argv); sdl3cpp::app::TraceLogger::SetEnabled(options.traceEnabled);