1 /* 2 * Copyright (c) 2021-2023 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 <map> 21 #include <mutex> 22 23 #include "io_waiter.h" 24 #include "nocopyable.h" 25 26 namespace OHOS { 27 namespace AppExecFwk { 28 // Use epoll to listen file descriptor. 29 class EpollIoWaiter final : public IoWaiter { 30 public: 31 EpollIoWaiter() = default; 32 ~EpollIoWaiter() final; 33 DISALLOW_COPY_AND_MOVE(EpollIoWaiter); 34 35 /** 36 * Initialize epoll. 37 * 38 * @return True if succeeded. 39 */ 40 bool Init(); 41 42 bool WaitFor(std::unique_lock<std::mutex> &lock, int64_t nanoseconds) final; 43 44 void NotifyOne() final; 45 void NotifyAll() final; 46 47 bool SupportListeningFileDescriptor() const final; 48 49 bool AddFileDescriptor(int32_t fileDescriptor, uint32_t events, const std::string &taskName) final; 50 void RemoveFileDescriptor(int32_t fileDescriptor) final; 51 52 void SetFileDescriptorEventCallback(const FileDescriptorEventCallback &callback) final; 53 void InsertTaskNameMap(int32_t fileDescriptor, const std::string& taskName); 54 void EraseTaskNameMap(int32_t fileDescriptor); 55 std::string GetTaskNameMap(int32_t fileDescriptor); 56 private: 57 void DrainAwakenPipe() const; 58 59 // File descriptor for epoll. 60 int32_t epollFd_{-1}; 61 // File descriptor used to wake up epoll. 62 int32_t awakenFd_{-1}; 63 std::mutex taskNameMapLock; 64 FileDescriptorEventCallback callback_; 65 std::atomic<int32_t> waitingCount_{0}; 66 std::map<int32_t, std::string> taskNameMap_; 67 }; 68 } // namespace AppExecFwk 69 } // namespace OHOS 70 71 #endif // #ifndef BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EPOLL_IO_WAITER_H 72