1 /* 2 * Copyright (C) 2022 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 #include <functional> 18 #include <map> 19 #include <mutex> 20 21 #include <fruit/fruit.h> 22 23 #include "common/libs/fs/epoll.h" 24 #include "common/libs/fs/shared_fd.h" 25 #include "common/libs/utils/result.h" 26 27 #pragma once 28 29 namespace cuttlefish { 30 31 using EpollCallback = std::function<Result<void>(EpollEvent)>; 32 33 class EpollPool { 34 public: 35 EpollPool(Epoll); 36 EpollPool(EpollPool&&); 37 EpollPool& operator=(EpollPool&&); 38 39 /** 40 * The `callback` function will be invoked with an EpollEvent containing `fd` 41 * and a subset of the bits in `events` matching which events were actually 42 * observed. The callback is invoked exactly once (enforced via EPOLLONESHOT) 43 * and must be re-`Register`ed to receive events again. This can be done 44 * in the callback implementation. Callbacks are invoked by callers of the 45 * `HandleEvent` function, and any errors produced by the callback function 46 * will manifest there. Callbacks that return errors will not be automatically 47 * re-registered. 48 */ 49 Result<void> Register(SharedFD fd, uint32_t events, EpollCallback callback); 50 Result<void> HandleEvent(); 51 Result<void> Remove(SharedFD fd); 52 53 private: 54 std::shared_mutex instance_mutex_; 55 Epoll epoll_; 56 std::mutex callbacks_mutex_; 57 std::map<SharedFD, EpollCallback> callbacks_; 58 }; 59 60 fruit::Component<EpollPool> EpollLoopComponent(); 61 62 } // namespace cuttlefish 63