OSDN Git Service

Remove fd from our tracking list when Thread is killed.
[android-x86/external-IA-Hardware-Composer.git] / common / utils / fdhandler.cpp
1 /*
2 // Copyright (c) 2017 Intel Corporation
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 "fdhandler.h"
18
19 #include <errno.h>
20 #include <poll.h>
21 #include <string.h>
22 #include <sys/types.h>
23
24 #include "hwctrace.h"
25
26 namespace hwcomposer {
27
28 FDHandler::FDHandler() {
29 }
30
31 FDHandler::~FDHandler() {
32 }
33
34 bool FDHandler::AddFd(int fd) {
35   if (fd < 0) {
36     ETRACE("Cannot add negative fd: %d", fd);
37     return false;
38   }
39
40   auto it = fds_.find(fd);
41   if (it != fds_.end()) {
42     ETRACE("FD already being watched: %d\n", it->first);
43     return false;
44   }
45
46   fds_.emplace(fd, FDWatch());
47
48   return true;
49 }
50
51 bool FDHandler::RemoveFd(int fd) {
52   const auto &fd_iter = fds_.find(fd);
53   if (fd_iter == fds_.end()) {
54     ETRACE("FD %d is not being watched.\n", fd);
55     return false;
56   }
57
58   fds_.erase(fd_iter);
59   return true;
60 }
61
62 int FDHandler::Poll(int timeout) {
63   nfds_t nfds = fds_.size();
64   struct pollfd fds[nfds];
65
66   int i = 0;
67   for (auto &it : fds_) {
68     fds[i].fd = it.first;
69     fds[i].events = POLLIN;
70     it.second.idx = i;
71     i++;
72   }
73
74   int ret = poll(fds, nfds, timeout);
75
76   for (auto &it : fds_) {
77     it.second.revents = fds[it.second.idx].revents;
78   }
79
80   return ret;
81 }
82
83 int FDHandler::IsReady(int fd) const {
84   const auto &it = fds_.find(fd);
85   if (it == fds_.end()) {
86     ETRACE("FD %d is being watched but we can't find it.\n", fd);
87     return false;
88   }
89
90   int revents = it->second.revents;
91   if (revents & POLLIN)
92     return 1;
93   else if (revents & POLLERR)
94     return -1;
95   else if (revents & POLLNVAL)
96     return -2;
97   else
98     return 0;
99 }
100
101 FDHandler::FDWatch::FDWatch() : revents(0), idx(0) {
102 }
103
104 }  // namespace hwcomposer