Coverage Report

Created: 2025-08-01 03:26

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/builds/MusicScience37Projects/utility-libraries/cpp-msgpack-rpc/src/msgpack_rpc/servers/stop_signal_handler.h
Line
Count
Source
1
/*
2
 * Copyright 2023 MusicScience37 (Kenta Kabashima)
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
/*!
17
 * \file
18
 * \brief Definition of StopSignalHandler class.
19
 */
20
#pragma once
21
22
#include <csignal>
23
#include <memory>
24
#include <utility>
25
26
#include <asio/error_code.hpp>
27
#include <asio/io_context.hpp>
28
#include <asio/signal_set.hpp>
29
30
#include "msgpack_rpc/logging/logger.h"
31
32
namespace msgpack_rpc::servers {
33
34
/*!
35
 * \brief Class to handle Linux signals SIGINT and SIGTERM to stop a server.
36
 */
37
class StopSignalHandler {
38
public:
39
    /*!
40
     * \brief Constructor.
41
     *
42
     * \param[in] logger Logger.
43
     */
44
    explicit StopSignalHandler(std::shared_ptr<logging::Logger> logger)
45
63
        : context_(1),
46
63
          signal_set_(context_, SIGINT, SIGTERM),
47
63
          logger_(std::move(logger)) {}
48
49
    /*!
50
     * \brief Wait for a signal SIGINT or SIGTERM.
51
     */
52
4
    void wait() {
53
4
        signal_set_.async_wait(
54
4
            [this](const asio::error_code& error, int signal_number) {
55
3
                if (!error) {
56
3
                    MSGPACK_RPC_DEBUG(
57
3
                        logger_, "Received signal {}.", signal_number);
58
3
                }
59
3
            });
60
4
        context_.run();
61
4
    }
62
63
    /*!
64
     * \brief Stop waiting.
65
     */
66
1
    void stop() { context_.stop(); }
67
68
private:
69
    //! Context of asio library.
70
    asio::io_context context_;
71
72
    //! Object to wait signals.
73
    asio::signal_set signal_set_;
74
75
    //! Logger.
76
    std::shared_ptr<logging::Logger> logger_;
77
};
78
79
}  // namespace msgpack_rpc::servers