• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef EPOLL_MANAGER_H_
17 #define EPOLL_MANAGER_H_
18 
19 #include <cstdint>
20 #include <list>
21 #include <memory>
22 #include <mutex>
23 
24 #include "smart_fd.h"
25 
26 namespace OHOS {
27 namespace HiviewDFX {
28 class EpollListener {
29 public:
30     explicit EpollListener(int32_t fd);
31     virtual ~EpollListener() = default;
32     virtual void OnEventPoll() = 0;
33     int32_t GetFd() const;
34 private:
35     const SmartFd fd_;
36 };
37 
38 class EpollManager {
39 public:
40     EpollManager() = default;
41     ~EpollManager();
42     EpollManager(const EpollManager&) = delete;
43     EpollManager& operator=(const EpollManager&) = delete;
44     EpollManager(EpollManager&&) noexcept = delete;
45     EpollManager& operator=(EpollManager&&) noexcept = delete;
46     bool Init(int maxPollEvent);
47     void StartEpoll(int maxConnection);
48     void StopEpoll();
49     bool AddListener(std::unique_ptr<EpollListener> epollListener);
50     bool RemoveListener(int32_t fd);
51 private:
52     bool AddEpollEvent(EpollListener& epollListener) const;
53     bool DelEpollEvent(int32_t fd) const;
54     EpollListener* GetTargetListener(int32_t fd);
55     std::list<std::unique_ptr<EpollListener>> listeners_;
56     int32_t eventFd_;
57     std::mutex epollMutex_;
58 };
59 
60 class DelayTask : public EpollListener {
61 public:
62     DelayTask(const DelayTask&) = delete;
63     DelayTask& operator=(const DelayTask&) = delete;
64     static std::unique_ptr<DelayTask> CreateInstance(std::function<void()> workFunc,
65         int32_t timeout, EpollManager& epollManager);
66     void OnEventPoll() override;
67 private:
68     DelayTask(std::function<void()> workFunc, int32_t timeFd, EpollManager& epollManager);
69     std::function<void()> work_;
70     EpollManager& epollManager_;
71 };
72 }
73 }
74 
75 #endif // EPOLL_MANAGER_H_
76