7
7
#include " server.hpp"
8
8
#include < fstream>
9
9
#include " ../main/Logger.h"
10
+ #include " ../main/Helper.h"
11
+ #include " ../main/localtime_r.h"
10
12
11
13
namespace http {
12
14
namespace server {
@@ -18,7 +20,8 @@ server_base::server_base(const server_settings & settings, request_handler & use
18
20
settings_ (settings),
19
21
request_handler_ (user_request_handler),
20
22
timeout_ (20 ), // default read timeout in seconds
21
- is_running (false ) {
23
+ is_running (false ),
24
+ is_stop_complete (false ) {
22
25
if (!settings.is_enabled ()) {
23
26
throw std::invalid_argument (" cannot initialize a disabled server (listening port cannot be empty or 0)" );
24
27
}
@@ -75,13 +78,27 @@ void server_base::run() {
75
78
76
79
// / Ask the server to stop using asynchronous command
77
80
void server_base::stop () {
78
- // Post a call to the stop function so that server_base::stop() is safe to call from any thread.
79
- io_service_.post (boost::bind (&server_base::handle_stop, this ));
80
- }
81
+ if (is_running) {
82
+ // Post a call to the stop function so that server_base::stop() is safe to call from any thread.
83
+ io_service_.post (boost::bind (&server_base::handle_stop, this ));
84
+ } else {
85
+ // if io_service is not running then the post call will not be performed
86
+ handle_stop ();
87
+ }
81
88
82
- // / Returns true if the server is stopped.
83
- bool server_base::stopped () {
84
- return !is_running;
89
+ // Wait for acceptor and connections to stop
90
+ int timeout = 15 ; // force stop after 15 seconds
91
+ time_t start = mytime (NULL );
92
+ while (true ) {
93
+ if (!is_running && is_stop_complete) {
94
+ break ;
95
+ }
96
+ if ((mytime (NULL ) - start) > timeout) {
97
+ // timeout occurred
98
+ break ;
99
+ }
100
+ sleep_milliseconds (500 );
101
+ }
85
102
}
86
103
87
104
void server_base::handle_stop () {
@@ -92,6 +109,7 @@ void server_base::handle_stop() {
92
109
_log.Log (LOG_ERROR, " [web:%s] exception occurred while closing acceptor" , settings_.listening_port .c_str ());
93
110
}
94
111
connection_manager_.stop_all (false );
112
+ is_stop_complete = true ;
95
113
}
96
114
97
115
server::server (const server_settings & settings, request_handler & user_request_handler) :
0 commit comments