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