Skip to content

Commit

Permalink
Handle SIGBREAK (Windows console close) (#2473)
Browse files Browse the repository at this point in the history
SetConsoleCtrlHandler is not needed because SIGBREAK is also sent
on window close. The process is killed when the thread handling
SIGBREAK returns. That's why we must handle it synchronously
and wait for other threads to finish first. The Windows-defined
timeout is only 5 seconds but there is no way to change that.

https://docs.microsoft.com/en-us/windows/console/ctrl-c-and-ctrl-break-signals

Fixes #1277
Fixes #1853
  • Loading branch information
DSpeichert committed Jul 5, 2018
1 parent bcb86ea commit b92d82a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/signals.cpp
Expand Up @@ -35,8 +35,12 @@
#include "globalevent.h"
#include "monster.h"
#include "events.h"
#include "scheduler.h"
#include "databasetasks.h"


extern Scheduler g_scheduler;
extern DatabaseTasks g_databaseTasks;
extern Dispatcher g_dispatcher;

extern ConfigManager g_config;
Expand All @@ -63,6 +67,11 @@ Signals::Signals(boost::asio::io_service& service) :
#ifndef _WIN32
set.add(SIGUSR1);
set.add(SIGHUP);
#else
// This must be a blocking call as Windows calls it in a new thread and terminates
// the process when the handler returns (or after 5 seconds, whichever is earlier).
// On Windows it is called in a new thread.
signal(SIGBREAK, dispatchSignalHandler);
#endif

asyncWait();
Expand All @@ -80,6 +89,9 @@ void Signals::asyncWait()
});
}

// On Windows this function does not need to be signal-safe,
// as it is called in a new thread.
// https://github.com/otland/forgottenserver/pull/2473
void Signals::dispatchSignalHandler(int signal)
{
switch(signal) {
Expand All @@ -96,12 +108,27 @@ void Signals::dispatchSignalHandler(int signal)
case SIGUSR1: //Saves game state
g_dispatcher.addTask(createTask(sigusr1Handler));
break;
#else
case SIGBREAK: //Shuts the server down
g_dispatcher.addTask(createTask(sigbreakHandler));
// hold the thread until other threads end
g_scheduler.join();
g_databaseTasks.join();
g_dispatcher.join();
break;
#endif
default:
break;
}
}

void Signals::sigbreakHandler()
{
//Dispatcher thread
std::cout << "SIGBREAK received, shutting game server down..." << std::endl;
g_game.setGameState(GAME_STATE_SHUTDOWN);
}

void Signals::sigtermHandler()
{
//Dispatcher thread
Expand Down
1 change: 1 addition & 0 deletions src/signals.h
Expand Up @@ -32,6 +32,7 @@ class Signals
void asyncWait();
static void dispatchSignalHandler(int signal);

static void sigbreakHandler();
static void sigintHandler();
static void sighupHandler();
static void sigtermHandler();
Expand Down

0 comments on commit b92d82a

Please sign in to comment.