1 /* 2 * Copyright (c) 2021-2022 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 BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EPOLL_IO_WAITER_H 17 #define BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EPOLL_IO_WAITER_H 18 19 #include <atomic> 20 #include <mutex> 21 22 #include "io_waiter.h" 23 #include "nocopyable.h" 24 25 #include <map> 26 #include <uv.h> 27 28 namespace OHOS { 29 namespace AppExecFwk { 30 // Use epoll to listen file descriptor. 31 class EpollIoWaiter final : public IoWaiter { 32 public: 33 EpollIoWaiter() = default; 34 ~EpollIoWaiter() final; 35 DISALLOW_COPY_AND_MOVE(EpollIoWaiter); 36 37 /** 38 * Initialize epoll. 39 * 40 * @return True if succeeded. 41 */ 42 bool Init(); 43 44 bool WaitFor(std::unique_lock<std::mutex> &lock, int64_t nanoseconds) final; 45 46 void NotifyOne() final; 47 void NotifyAll() final; 48 49 bool SupportListeningFileDescriptor() const final; 50 51 bool AddFileDescriptor(int32_t fd, uint32_t events) final; 52 void RemoveFileDescriptor(int32_t fd) final; 53 54 void SetFileDescriptorEventCallback(const FileDescriptorEventCallback &callback) final; 55 56 private: 57 static void OnPoll(uv_poll_t *poll, int status, int events); 58 static void OnTimer(uv_timer_t *timer); 59 static void OnSignal(uv_signal_t *signal, int32_t signum); 60 template<typename T> GetInstance(T * that)61 static EpollIoWaiter &GetInstance(T *that) 62 { 63 return *reinterpret_cast<EpollIoWaiter *>(that->data); 64 } 65 66 uv_loop_t loop_ = {.data = this}; 67 uv_signal_t signal_ = {.data = this}; 68 uv_timer_t timer_ = {.data = this}; 69 std::mutex timerMutex_; 70 std::map<int32_t, uv_poll_t> pollMap_; 71 bool overtime = false; 72 FileDescriptorEventCallback fdcallback_ = nullptr; 73 }; 74 } // namespace AppExecFwk 75 } // namespace OHOS 76 77 #endif // #ifndef BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EPOLL_IO_WAITER_H 78