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 <sys/epoll.h> 24 #include "io_waiter.h" 25 #include "nocopyable.h" 26 #include "event_queue.h" 27 #include "file_descriptor_listener.h" 28 29 #define LOCAL_API __attribute__((visibility ("hidden"))) 30 namespace OHOS { 31 namespace AppExecFwk { 32 class EventHandler; 33 34 // Use epoll to listen file descriptor. 35 class EpollIoWaiter final : public IoWaiter { 36 public: 37 EpollIoWaiter() = default; 38 ~EpollIoWaiter() final; 39 DISALLOW_COPY_AND_MOVE(EpollIoWaiter); 40 41 /** 42 * Initialize epoll. 43 * 44 * @return True if succeeded. 45 */ 46 LOCAL_API bool Init(); 47 48 LOCAL_API bool WaitFor(std::unique_lock<std::mutex> &lock, int64_t nanoseconds) final; 49 50 LOCAL_API void NotifyOne() final; 51 LOCAL_API void NotifyAll() final; 52 bool SupportListeningFileDescriptor() const final; 53 54 LOCAL_API bool AddFileDescriptor(int32_t fileDescriptor, uint32_t events, const std::string &taskName, 55 const std::shared_ptr<FileDescriptorListener>& listener, EventQueue::Priority priority) final; 56 void RemoveFileDescriptor(int32_t fileDescriptor) final; 57 58 LOCAL_API void SetFileDescriptorEventCallback(const FileDescriptorEventCallback &callback) final; 59 LOCAL_API void InsertFileDescriptorMap(int32_t fileDescriptor, const std::string& taskName, 60 EventQueue::Priority priority, const std::shared_ptr<FileDescriptorListener>& listener); 61 LOCAL_API void EraseFileDescriptorMap(int32_t fileDescriptor); 62 LOCAL_API std::shared_ptr<FileDescriptorInfo> GetFileDescriptorMap(int32_t fileDescriptor) override; 63 private: 64 LOCAL_API void DrainAwakenPipe() const; 65 66 // File descriptor for epoll. 67 int32_t epollFd_{-1}; 68 // File descriptor used to wake up epoll. 69 int32_t awakenFd_{-1}; 70 std::mutex fileDescriptorMapLock; 71 FileDescriptorEventCallback callback_; 72 std::atomic<int32_t> waitingCount_{0}; 73 std::map<int32_t, std::shared_ptr<FileDescriptorInfo>> fileDescriptorMap_; 74 }; 75 } // namespace AppExecFwk 76 } // namespace OHOS 77 78 #endif // #ifndef BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EPOLL_IO_WAITER_H 79