Explorar el Código

device: add handlers for SIGINT, SIGTERM and CTRL_C

Daniele Bartolini hace 3 años
padre
commit
ff6425d476
Se han modificado 3 ficheros con 50 adiciones y 0 borrados
  1. 3 0
      src/device/device.cpp
  2. 31 0
      src/device/main_linux.cpp
  3. 16 0
      src/device/main_windows.cpp

+ 3 - 0
src/device/device.cpp

@@ -537,6 +537,9 @@ void Device::run()
 void Device::quit()
 {
 	_quit = true;
+
+	if (_console_server)
+		_console_server->close();
 }
 
 void Device::pause()

+ 31 - 0
src/device/main_linux.cpp

@@ -33,6 +33,7 @@
 #include <X11/Xutil.h>
 #define STB_SPRINTF_IMPLEMENTATION
 #include <stb_sprintf.h>
+#include <signal.h>
 
 namespace crown
 {
@@ -954,6 +955,32 @@ struct InitGlobals
 int main(int argc, char **argv)
 {
 	using namespace crown;
+
+	struct sigaction old_SIGINT;
+	struct sigaction old_SIGTERM;
+	struct sigaction act;
+	// code-format off
+	act.sa_handler = [](int signum) {
+			switch (signum)
+			{
+			case SIGINT:
+			case SIGTERM:
+				if (device())
+					device()->quit();
+				break;
+
+			default:
+				break;
+			}
+		};
+	// code-format on
+	sigemptyset(&act.sa_mask);
+	act.sa_flags = 0;
+	sigaction(SIGINT, NULL, &old_SIGINT);
+	sigaction(SIGINT, &act, NULL);
+	sigaction(SIGTERM, NULL, &old_SIGTERM);
+	sigaction(SIGTERM, &act, NULL);
+
 #if CROWN_BUILD_UNIT_TESTS
 	CommandLine cl(argc, (const char **)argv);
 	if (cl.has_option("run-unit-tests")) {
@@ -985,6 +1012,10 @@ int main(int argc, char **argv)
 		CE_DELETE(default_allocator(), s_linux_device);
 	}
 
+	// Restore original signal handlers.
+	sigaction(SIGINT, &old_SIGINT, NULL);
+	sigaction(SIGTERM, &old_SIGTERM, NULL);
+
 	return ec;
 }
 

+ 16 - 0
src/device/main_windows.cpp

@@ -825,6 +825,21 @@ int main(int argc, char **argv)
 		freopen("CONOUT$", "w", stderr);
 	}
 
+	// code-format off
+	PHANDLER_ROUTINE signal_handler = [](DWORD dwCtrlType) {
+			switch (dwCtrlType) {
+			case CTRL_C_EVENT:
+				if (device())
+					device()->quit();
+				return TRUE;
+
+			default:
+				return FALSE;
+			}
+		};
+	// code-format on
+	SetConsoleCtrlHandler(signal_handler, TRUE);
+
 	WSADATA wsdata;
 	int err = WSAStartup(MAKEWORD(2, 2), &wsdata);
 	CE_ASSERT(err == 0, "WSAStartup: error = %d", err);
@@ -864,6 +879,7 @@ int main(int argc, char **argv)
 
 	FreeConsole();
 	WSACleanup();
+	SetConsoleCtrlHandler(signal_handler, FALSE);
 	return ec;
 }