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/log/log.h>
29 DescriptorSet::DescriptorSet() : m_dirty(true), m_fds(NULL) {
32 DescriptorSet::~DescriptorSet() {
36 void DescriptorSet::purge() {
37 for(auto it:m_descriptors)
39 m_descriptors.clear();
42 void DescriptorSet::add(int fd, short events, Callback&& callback) {
43 // map operator[] requires empty DescriptorData constructor
44 auto it = m_descriptors.find(fd);
45 if (it == m_descriptors.end()) {
46 m_descriptors.insert(std::make_pair(fd,DescriptorData(events, std::move(callback))));
48 it->second.events = events;
49 it->second.callback = std::move(callback);
54 void DescriptorSet::remove(int fd, bool close_fd) {
55 if (0 != m_descriptors.erase(fd)) {
62 void DescriptorSet::wait(int timeout_ms) {
67 int ret = TEMP_FAILURE_RETRY(poll(m_fds, m_descriptors.size(), timeout_ms));
69 ThrowMsg(Timeout, "Poll timeout");
72 ThrowMsg(InternalError, "Poll failed " << strerror(err));
78 bool DescriptorSet::rebuildPollfd() {
82 if (m_descriptors.empty()) {
83 LogWarning("Nothing to wait for");
87 m_fds = new pollfd[m_descriptors.size()];
89 for(const auto& it : m_descriptors) {
90 m_fds[idx].fd = it.first;
91 m_fds[idx].events = it.second.events;
99 void DescriptorSet::notify(int descCount) {
100 size_t size = m_descriptors.size();
101 for(size_t idx = 0;idx < size;++idx) {
102 const pollfd& pfd = m_fds[idx];
103 if (pfd.revents == 0)
107 * Descriptors can be added/removed inside observer callback but:
108 * 1. m_fds is not affected. It will be regenerated in next wait()
109 * 2. No m_descriptors iterator will be invalidated
110 * 3. m_descriptors size is stored in local variable
112 m_descriptors.at(pfd.fd).callback(pfd.fd, pfd.revents);
115 // no more descriptors to check
120 ThrowMsg(InternalError, "Number of notified descriptors do not match");
123 } /* namespace CKM */