diff options
Diffstat (limited to 'examples/response-sample.cpp')
-rw-r--r-- | examples/response-sample.cpp | 41 |
1 files changed, 37 insertions, 4 deletions
diff --git a/examples/response-sample.cpp b/examples/response-sample.cpp index c3ef177..883d821 100644 --- a/examples/response-sample.cpp +++ b/examples/response-sample.cpp @@ -2,7 +2,9 @@ // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. - +#ifndef VSOMEIP_ENABLE_SIGNAL_HANDLING +#include <csignal> +#endif #include <chrono> #include <condition_variable> #include <iomanip> @@ -21,6 +23,7 @@ public: is_registered_(false), use_static_routing_(_use_static_routing), blocked_(false), + running_(true), offer_thread_(std::bind(&service_sample::run, this)) { } @@ -44,6 +47,19 @@ public: app_->start(); } +#ifndef VSOMEIP_ENABLE_SIGNAL_HANDLING + /* + * Handle signal to shutdown + */ + void stop() { + running_ = false; + blocked_ = true; + condition_.notify_one(); + offer_thread_.join(); + app_->stop(); + } +#endif + void offer() { app_->offer_service(SAMPLE_SERVICE_ID, SAMPLE_INSTANCE_ID); app_->offer_service(SAMPLE_SERVICE_ID + 1, SAMPLE_INSTANCE_ID); @@ -101,14 +117,16 @@ public: if (use_static_routing_) { offer(); - while (true); + while (running_); } else { - while (true) { + while (running_) { if (is_offer) offer(); else stop_offer(); - std::this_thread::sleep_for(std::chrono::milliseconds(10000)); + + for (int i = 0; i < 10 && running_; i++) + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); is_offer = !is_offer; } } @@ -122,11 +140,21 @@ private: std::mutex mutex_; std::condition_variable condition_; bool blocked_; + bool running_; // blocked_ must be initialized before the thread is started. std::thread offer_thread_; }; +#ifndef VSOMEIP_ENABLE_SIGNAL_HANDLING + service_sample *its_sample_ptr(nullptr); + void handle_signal(int _signal) { + if (its_sample_ptr != nullptr && + (_signal == SIGINT || _signal == SIGTERM)) + its_sample_ptr->stop(); + } +#endif + int main(int argc, char **argv) { bool use_static_routing(false); @@ -139,6 +167,11 @@ int main(int argc, char **argv) { } service_sample its_sample(use_static_routing); +#ifndef VSOMEIP_ENABLE_SIGNAL_HANDLING + its_sample_ptr = &its_sample; + signal(SIGINT, handle_signal); + signal(SIGTERM, handle_signal); +#endif its_sample.init(); its_sample.start(); |