1 /*
2  * Copyright (C) 2024 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 "host/commands/process_sandboxer/poll_callback.h"
18 
19 #include <poll.h>
20 
21 #include <functional>
22 #include <vector>
23 
24 #include <absl/log/log.h>
25 #include <absl/status/status.h>
26 
27 namespace cuttlefish {
28 namespace process_sandboxer {
29 
Add(int fd,std::function<absl::Status (short)> cb)30 void PollCallback::Add(int fd, std::function<absl::Status(short)> cb) {
31   pollfds_.emplace_back(pollfd{
32       .fd = fd,
33       .events = POLLIN,
34   });
35   callbacks_.emplace_back(std::move(cb));
36 }
37 
Poll()38 absl::Status PollCallback::Poll() {
39   int poll_ret = poll(pollfds_.data(), pollfds_.size(), 0);
40   if (poll_ret < 0) {
41     return absl::Status(absl::ErrnoToStatusCode(errno), "`poll` failed");
42   }
43 
44   VLOG(2) << "`poll` returned " << poll_ret;
45 
46   for (size_t i = 0; i < pollfds_.size() && i < callbacks_.size(); i++) {
47     const auto& poll_fd = pollfds_[i];
48     if (poll_fd.revents == 0) {
49       continue;
50     }
51     auto status = callbacks_[i](poll_fd.revents);
52     if (!status.ok()) {
53       return status;
54     }
55   }
56   return absl::OkStatus();
57 }
58 
59 }  // namespace process_sandboxer
60 }  // namespace cuttlefish
61