-
Notifications
You must be signed in to change notification settings - Fork 2
/
INotify.cpp
59 lines (45 loc) · 1.34 KB
/
INotify.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// SPDX-FileCopyrightText: 2018 Lutz Freitag
// SPDX-License-Identifier: MIT
#include "INotify.h"
#include <linux/limits.h>
#include <algorithm>
#include <array>
#include <cerrno>
namespace simplyfile {
INotify::INotify(int flags)
: FileDescriptor(::inotify_init1(flags))
{}
void INotify::watch(std::string const& _path, uint32_t mask) {
int id = inotify_add_watch(*this, _path.c_str(), mask);
mIDs[id] = _path;
}
void INotify::unwatch(std::string const& _path) {
auto it = std::find_if(mIDs.begin(), mIDs.end(), [&](auto const& p) { return p.second == _path; });
if (it == mIDs.end()) {
return;
}
inotify_rm_watch(*this, it->first);
}
void INotify::unwatch_all() {
for (auto const& [id, p] : mIDs) {
inotify_rm_watch(*this, id);
}
}
auto INotify::readEvent() -> std::optional<INotify::Result> {
std::array<std::byte, sizeof(inotify_event) + NAME_MAX + 1> buffer;
int r = read(*this, buffer.data(), buffer.size());
if (r <= 0 and (errno == EAGAIN || errno == EWOULDBLOCK)) {
return {};
}
inotify_event const& event = *reinterpret_cast<inotify_event const*>(buffer.data());
if (0 == event.wd) {
return std::nullopt;
}
INotify::Result res;
res.path = mIDs.at(event.wd);
if (event.len > 0) {
res.file = event.name;
}
return res;
}
}