Belle II Software development
Inotify.cc
1/**************************************************************************
2 * basf2 (Belle II Analysis Software Framework) *
3 * Author: The Belle II Collaboration *
4 * *
5 * See git log for contributors and copyright holders. *
6 * This file is licensed under LGPL-3.0, see LICENSE.md. *
7 **************************************************************************/
8#include "daq/slc/system/Inotify.h"
9
10#include <daq/slc/base/IOException.h>
11
12#include <sys/inotify.h>
13#include <unistd.h>
14
15using namespace Belle2;
16
17const unsigned long Inotify::FILE_CREATE(IN_CREATE);
18const unsigned long Inotify::FILE_OPEN(IN_OPEN);
19const unsigned long Inotify::FILE_CLOSE_WRITE(IN_CLOSE_WRITE);
20const unsigned long Inotify::FILE_CLOSE_NOWRITE(IN_CLOSE_NOWRITE);
21const unsigned long Inotify::FILE_DELETE(IN_DELETE);
22const unsigned long Inotify::FILE_MODIFY(IN_MODIFY);
23const unsigned long Inotify::FILE_ACCESS(IN_ACCESS);
24const unsigned long Inotify::FILE_ATTRIB(IN_ATTRIB);
25
26void Inotify::open()
27{
28 if ((m_fd = ::inotify_init()) < 0) {
29 throw (IOException("Failed to initialize inotify."));
30 }
31}
32
33int Inotify::add(const std::string& path, unsigned long mask)
34{
35 int wd = inotify_add_watch(m_fd, path.c_str(), mask);
36 if (wd < 0) {
37 throw (IOException("Failed to add a path"));
38 }
39 return wd;
40}
41
42void Inotify::remove(int wd)
43{
44 if (::inotify_rm_watch(m_fd, wd) < 0) {
45 throw (IOException("Failed to remove a path"));
46 }
47}
48
49InotifyEventList Inotify::wait(int sec)
50{
51 InotifyEventList ievent_v;
52 //try {
53 if (select(sec, 0)) {
54 char buf[16384];
55 int r = read(m_fd, buf, 16384);
56 if (r <= 0) return ievent_v;
57 int index = 0;
58 while (index < r) {
59 inotify_event* ev = (inotify_event*)&buf[index];
60 int event_size = sizeof(inotify_event) + ev->len;
61 index += event_size;
62 ievent_v.push_back(InotifyEvent(ev->wd, ev->mask, ev->name));
63 }
64 }
65 //} catch (const IOException& e) {
66 //std::cerr << "Failed to select" << std::endl;
67 //}
68 return ievent_v;
69}
Abstract base class for different kinds of events.