2 * Copyright (c) 2000 - 2014 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
17 * @file descriptor-set.cpp
18 * @author Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
22 #include "descriptor-set.h"
23 #include <dpl/errno_string.h>
24 #include <dpl/log/log.h>
30 DescriptorSet::DescriptorSet() : m_dirty(true), m_fds(NULL)
34 DescriptorSet::~DescriptorSet()
41 void DescriptorSet::purge()
43 for (auto it : m_descriptors)
46 m_descriptors.clear();
50 void DescriptorSet::add(int fd, short events, Callback &&callback)
52 // map operator[] requires empty DescriptorData constructor
53 auto it = m_descriptors.find(fd);
55 if (it == m_descriptors.end()) {
56 m_descriptors.insert(std::make_pair(fd, DescriptorData(events,
57 std::move(callback))));
59 it->second.events = events;
60 it->second.callback = std::move(callback);
66 void DescriptorSet::remove(int fd, bool close_fd)
68 if (0 != m_descriptors.erase(fd)) {
76 void DescriptorSet::wait(int timeout_ms)
82 int ret = TEMP_FAILURE_RETRY(poll(m_fds, m_descriptors.size(), timeout_ms));
85 ThrowMsg(Timeout, "Poll timeout");
88 ThrowMsg(InternalError, "Poll failed " << GetErrnoString(err));
94 bool DescriptorSet::rebuildPollfd()
100 if (m_descriptors.empty()) {
101 LogWarning("Nothing to wait for");
105 m_fds = new pollfd[m_descriptors.size()];
108 for (const auto &it : m_descriptors) {
109 m_fds[idx].fd = it.first;
110 m_fds[idx].events = it.second.events;
120 void DescriptorSet::notify(int descCount)
122 size_t size = m_descriptors.size();
124 for (size_t idx = 0; idx < size; ++idx) {
125 const pollfd &pfd = m_fds[idx];
127 if (pfd.revents == 0)
131 * Descriptors can be added/removed inside observer callback but:
132 * 1. m_fds is not affected. It will be regenerated in next wait()
133 * 2. No m_descriptors iterator will be invalidated
134 * 3. m_descriptors size is stored in local variable
136 m_descriptors.at(pfd.fd).callback(pfd.fd, pfd.revents);
139 // no more descriptors to check
145 ThrowMsg(InternalError, "Number of notified descriptors do not match");
148 } /* namespace CKM */