plptools
Loading...
Searching...
No Matches
iowatch.cc
Go to the documentation of this file.
1/*
2 * This file is part of plptools.
3 *
4 * Copyright (C) 1999 Philip Proudman <philip.proudman@btinternet.com>
5 * Copyright (C) 2000, 2001 Fritz Elfert <felfert@to.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * along with this program; if not, see <https://www.gnu.org/licenses/>.
19 *
20 */
21#include "config.h"
22
23#include "iowatch.h"
24
25#include <mutex>
26#include <unistd.h>
27#include <stdio.h>
28#include <sys/time.h>
29#include <sys/types.h>
30#include <memory.h>
31
34 fileDescriptors_ = new int [FD_SETSIZE];
35 memset(fileDescriptors_, -1, FD_SETSIZE);
36}
37
39 delete [] fileDescriptors_;
40}
41
42void IOWatch::addIO(const int fd) {
43 std::lock_guard<std::mutex> lock(lock_);
44 int pos;
45 for (pos = 0; pos < fileDescriptorCount_ && fd < fileDescriptors_[pos]; pos++);
46 if (fileDescriptors_[pos] == fd)
47 return;
48 for (int i = fileDescriptorCount_; i > pos; i--)
50 fileDescriptors_[pos] = fd;
52}
53
54void IOWatch::remIO(const int fd) {
55 std::lock_guard<std::mutex> lock(lock_);
56 int pos;
57 for (pos = 0; pos < fileDescriptorCount_ && fd != fileDescriptors_[pos]; pos++);
58 if (pos != fileDescriptorCount_) {
60 for (int i = pos; i <fileDescriptorCount_; i++) fileDescriptors_[i] = fileDescriptors_[i+1];
61 }
62}
63
64bool IOWatch::watch(const long secs, const long usecs) {
65 int maxfd = 0;
66 fd_set iop;
67 FD_ZERO(&iop);
68 {
69 std::lock_guard<std::mutex> lock(lock_);
70 for (int i = 0; i < fileDescriptorCount_; i++) {
71 FD_SET(fileDescriptors_[i], &iop);
72 if (fileDescriptors_[i] > maxfd) {
73 maxfd = fileDescriptors_[i];
74 }
75 }
76 }
77 struct timeval t;
78 t.tv_usec = usecs;
79 t.tv_sec = secs;
80 return select(maxfd + 1, &iop, NULL, NULL, &t) > 0;
81}
int fileDescriptorCount_
Definition: iowatch.h:74
IOWatch()
Creates a new instance.
Definition: iowatch.cc:32
std::mutex lock_
Definition: iowatch.h:73
void remIO(const int fd)
Removes a file descriptor from the set of descriptors.
Definition: iowatch.cc:54
void addIO(const int fd)
Adds a file descriptor to the set of descriptors.
Definition: iowatch.cc:42
bool watch(const long secs, const long usecs)
Performs a select() call.
Definition: iowatch.cc:64
~IOWatch()
Destroys an instance.
Definition: iowatch.cc:38
int * fileDescriptors_
Definition: iowatch.h:75