blob: 1e71803f6b50e58cac537624e0e47a6223c0644b [file] [log] [blame]
Mark Salyzyn6c6ec722015-10-24 16:20:18 -07001/*
2 * Copyright (C) 2018 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
Tom Cherry905a5df2019-08-30 14:12:56 -070017#pragma once
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070018
Mark Salyzyn37bbf802019-03-13 07:25:52 -070019#include <stdint.h>
20#include <sys/epoll.h>
21
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070022#include <chrono>
23#include <functional>
24#include <map>
David Anderson1de73842021-05-13 20:18:14 -070025#include <memory>
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070026#include <optional>
Bart Van Asschebc5c4a42022-10-14 09:13:19 -070027#include <unordered_set>
Tom Cherry905a5df2019-08-30 14:12:56 -070028#include <vector>
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070029
30#include <android-base/unique_fd.h>
31
32#include "result.h"
33
34namespace android {
35namespace init {
36
37class Epoll {
38 public:
39 Epoll();
40
David Anderson1de73842021-05-13 20:18:14 -070041 typedef std::function<void()> Handler;
42
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070043 Result<void> Open();
David Anderson1de73842021-05-13 20:18:14 -070044 Result<void> RegisterHandler(int fd, Handler handler, uint32_t events = EPOLLIN);
Tom Cherrybbcbc2f2019-06-10 11:08:01 -070045 Result<void> UnregisterHandler(int fd);
Bart Van Asschea2c16042022-10-14 09:35:35 -070046 void SetFirstCallback(std::function<void()> first_callback);
Bart Van Asschebc5c4a42022-10-14 09:13:19 -070047 Result<int> Wait(std::optional<std::chrono::milliseconds> timeout);
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070048
49 private:
David Anderson0fa7c402022-03-07 19:10:57 -080050 struct Info {
Bart Van Asschedcd23df2022-10-14 12:55:35 -070051 Handler handler;
David Anderson0fa7c402022-03-07 19:10:57 -080052 uint32_t events;
53 };
54
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070055 android::base::unique_fd epoll_fd_;
David Anderson0fa7c402022-03-07 19:10:57 -080056 std::map<int, Info> epoll_handlers_;
Bart Van Asschea2c16042022-10-14 09:35:35 -070057 std::function<void()> first_callback_;
Bart Van Asschebc5c4a42022-10-14 09:13:19 -070058 std::unordered_set<int> to_remove_;
Mark Salyzyn6c6ec722015-10-24 16:20:18 -070059};
60
61} // namespace init
62} // namespace android