fd_watcher.cpp
Go to the documentation of this file.
1 // Watches a set of file descriptors for changes
2 // Author: Max Schwarz <max.schwarz@uni-bonn.de>
3 
4 #include "fd_watcher.h"
5 
6 #include <cstdarg>
7 #include <vector>
8 
9 #include <sys/types.h>
10 #include <sys/select.h>
11 
12 #include <fmt/format.h>
13 
14 template<typename... Args>
15 std::runtime_error error(const char* fmt, const Args& ... args)
16 {
17  return std::runtime_error(fmt::format(fmt, args...));
18 }
19 
20 namespace rosmon
21 {
22 
24 {
25 }
26 
27 void FDWatcher::registerFD(int fd, const boost::function<void (int)>& cb)
28 {
29  m_fds[fd] = cb;
30 }
31 
32 void FDWatcher::removeFD(int fd)
33 {
34  m_fds.erase(fd);
35 }
36 
37 void FDWatcher::wait(const ros::WallDuration& duration)
38 {
39  timeval timeout;
40  timeout.tv_sec = duration.toNSec() / 1000LL / 1000LL / 1000LL;
41  timeout.tv_usec = (duration.toNSec() / 1000LL) % (1000LL * 1000LL * 1000LL);
42 
43  fd_set fds;
44  FD_ZERO(&fds);
45 
46  int maxfd = 0;
47  for(auto pair : m_fds)
48  {
49  FD_SET(pair.first, &fds);
50  maxfd = std::max(pair.first, maxfd);
51  }
52 
53  int ret = select(maxfd+1, &fds, nullptr, nullptr, &timeout);
54  if(ret < 0)
55  {
56  if(errno == EINTR || errno == EAGAIN)
57  return;
58 
59  throw error("Could not select(): {}", strerror(errno));
60  }
61 
62  if(ret != 0)
63  {
64  // Store the callbacks to be notified in a temporary list, as calling
65  // the callback might call removeFD(), which will confuse us...
66  std::vector<std::pair<int, boost::function<void(int)>>> toBeNotified;
67 
68  for(auto pair : m_fds)
69  {
70  if(FD_ISSET(pair.first, &fds))
71  toBeNotified.emplace_back(pair);
72  }
73 
74  // Actually call the callbacks
75  for(auto pair : toBeNotified)
76  pair.second(pair.first);
77  }
78 }
79 
80 }
void wait(const ros::WallDuration &duration)
Definition: fd_watcher.cpp:37
std::map< int, boost::function< void(int)> > m_fds
Definition: fd_watcher.h:28
void registerFD(int fd, const boost::function< void(int)> &cb)
Definition: fd_watcher.cpp:27
std::runtime_error error(const char *fmt, const Args &...args)
Definition: fd_watcher.cpp:15
void removeFD(int fd)
Definition: fd_watcher.cpp:32


rosmon_core
Author(s): Max Schwarz
autogenerated on Wed Jul 10 2019 03:10:12