Skip to content

Commit 9478f66

Browse files
authored
Merge pull request #23 from Ataba29/dockerStopping
Added watching kill signal and shutdown gracefully
2 parents dd9bf1e + b8f29f6 commit 9478f66

1 file changed

Lines changed: 35 additions & 12 deletions

File tree

src/main.cpp

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,22 @@
1+
#include <atomic>
2+
#include <csignal>
13
#include <iostream>
24
#include <string>
35
#include <thread>
6+
#include <chrono>
47

58
#include "RAM/HashMap.h"
69
#include "Server/Server.h"
710

11+
namespace
12+
{
13+
std::atomic<bool> shutdownRequested{false};
14+
void handleSignal(int)
15+
{
16+
shutdownRequested.store(true, std::memory_order_relaxed);
17+
}
18+
}
19+
820
int main()
921
{
1022
int port = 6625;
@@ -13,29 +25,40 @@ int main()
1325

1426
server.start();
1527

28+
std::signal(SIGTERM, handleSignal);
29+
std::signal(SIGINT, handleSignal);
30+
1631
// Run accept loop in background thread
1732
std::thread serverThread(&Server::acceptClients, &server);
1833

1934
std::cout << "[MAIN] Server running. Type 'stop' to shut it down.\n";
2035

21-
std::string cmd;
22-
23-
while (true)
24-
{
25-
std::cin >> cmd;
26-
27-
if (cmd == "stop")
36+
std::thread stdinThread([]{
37+
std::string cmd;
38+
while(!shutdownRequested.load(std::memory_order_relaxed))
2839
{
29-
std::cout << "[MAIN] Stopping server...\n";
30-
31-
server.stop();
32-
33-
break;
40+
// The application was ran from docker
41+
if(!(std::cin >> cmd))
42+
break;
43+
44+
// This application is running on terminal use old logic to shut down
45+
if(cmd == "stop"){
46+
shutdownRequested.store(true, std::memory_order_relaxed);
47+
break;
48+
}
3449
}
50+
});
51+
52+
while(!shutdownRequested.load(std::memory_order_relaxed)){
53+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
3554
}
55+
56+
std::cout << "[MAIN] Stopping server...\n";
57+
server.stop();
3658

3759
// Wait for server thread to finish
3860
serverThread.join();
61+
stdinThread.detach();
3962

4063
std::cout << "[MAIN] Server exited cleanly\n";
4164

0 commit comments

Comments
 (0)