mirror of
https://github.com/johndoe6345789/SDL3CPlusPlus.git
synced 2026-04-24 13:44:58 +00:00
Implement signal handling to gracefully stop the application
This commit is contained in:
@@ -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 {
|
||||
|
||||
@@ -2,7 +2,9 @@
|
||||
#include "app/sdl3_app.hpp"
|
||||
#include "app/trace.hpp"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
@@ -14,6 +16,8 @@
|
||||
|
||||
namespace sdl3cpp::app {
|
||||
|
||||
extern std::atomic<bool> g_signalReceived;
|
||||
|
||||
std::vector<char> 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) {
|
||||
|
||||
18
src/main.cpp
18
src/main.cpp
@@ -5,6 +5,8 @@
|
||||
#include <rapidjson/writer.h>
|
||||
#include <rapidjson/prettywriter.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <csignal>
|
||||
#include <cstdlib>
|
||||
#include <cstdint>
|
||||
#include <exception>
|
||||
@@ -20,8 +22,23 @@
|
||||
#include "app/sdl3_app.hpp"
|
||||
#include <SDL3/SDL_main.h>
|
||||
|
||||
namespace sdl3cpp::app {
|
||||
std::atomic<bool> 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);
|
||||
|
||||
Reference in New Issue
Block a user