• 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 <functional>
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(SmartFd fd, bool persist = false);
31     virtual ~EpollListener() = default;
32     virtual void OnEventPoll() = 0;
33     virtual bool IsPersist() const final;
34     int32_t GetFd() const;
35 private:
36     const SmartFd fd_;
37     bool persist_{false};
38 };
39 
40 class EpollManager {
41 public:
42     EpollManager() = default;
43     ~EpollManager();
44     EpollManager(const EpollManager&) = delete;
45     EpollManager& operator=(const EpollManager&) = delete;
46     EpollManager(EpollManager&&) noexcept = delete;
47     EpollManager& operator=(EpollManager&&) noexcept = delete;
48     bool Init(int maxPollEvent);
49     void StartEpoll(int maxConnection, int epollTimeoutInMilliseconds = -1);
50     void StopEpoll();
51     bool AddListener(std::unique_ptr<EpollListener> epollListener);
52     bool RemoveListener(int32_t fd);
53 private:
54     bool AddEpollEvent(EpollListener& epollListener) const;
55     bool DelEpollEvent(int32_t fd) const;
56     EpollListener* GetTargetListener(int32_t fd);
57     std::list<std::unique_ptr<EpollListener>> listeners_;
58     SmartFd eventFd_;
59     std::mutex epollMutex_;
60 };
61 
62 class DelayTask : public EpollListener {
63 public:
64     DelayTask(const DelayTask&) = delete;
65     DelayTask& operator=(const DelayTask&) = delete;
66     static std::unique_ptr<DelayTask> CreateInstance(std::function<void()> workFunc, int32_t timeout);
67     void OnEventPoll() override;
68 private:
69     DelayTask(std::function<void()> workFunc, SmartFd timeFd);
70     std::function<void()> work_;
71 };
72 }
73 }
74 
75 #endif // EPOLL_MANAGER_H_
76