Skip to content

Commit 3f60f0b

Browse files
committed
fix UB
Only safe asynchronous functions are allowed to be called in signal handlers Signed-off-by: 𝓈𝒽𝓎𝓃𝓊𝓇 <shynur@outlook.com>
1 parent 15ffb89 commit 3f60f0b

1 file changed

Lines changed: 11 additions & 11 deletions

File tree

code/Examples/C++/RpcClientServerBasic/src/CalculatorServer.cpp

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@
1212
// See the License for the specific language governing permissions and
1313
// limitations under the License.
1414

15+
#include <atomic>
16+
#include <chrono>
1517
#include <csignal>
16-
#include <functional>
1718
#include <iostream>
1819
#include <memory>
1920
#include <string>
@@ -143,12 +144,13 @@ class Server
143144
//!--
144145
};
145146

146-
std::function<void(int)> stop_handler;
147+
volatile std::sig_atomic_t stop_requested = 0;
147148

148149
void signal_handler(
149150
int signum)
150151
{
151-
stop_handler(signum);
152+
(void)signum;
153+
stop_requested = 1;
152154
}
153155

154156
//!--MAIN
@@ -163,12 +165,6 @@ int main(
163165

164166
std::thread thread(&Server::run, server);
165167

166-
stop_handler = [&](int signum)
167-
{
168-
std::cout << "Signal received, stopping execution." << std::endl;
169-
server->stop();
170-
};
171-
172168
signal(SIGINT, signal_handler);
173169
signal(SIGTERM, signal_handler);
174170
#ifndef _WIN32
@@ -178,8 +174,12 @@ int main(
178174

179175
std::cout << "Server running. Please press Ctrl+C to stop the server at any time." << std::endl;
180176

177+
while (!stop_requested)
178+
{
179+
std::this_thread::sleep_for(std::chrono::milliseconds(100));
180+
}
181+
std::cout << "Signal received, stopping execution." << std::endl;
182+
server->stop();
181183
thread.join();
182-
183-
return 0;
184184
}
185185
//!--

0 commit comments

Comments
 (0)