-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathinotify.lua
104 lines (81 loc) · 2.41 KB
/
inotify.lua
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
local ffi = require("ffi")
local C = ffi.C
local IN = require("ljclang_linux_decls").IN
local class = require("class").class
local check = require("error_util").check
local posix = require("posix")
local assert = assert
local error = error
local tonumber = tonumber
local tostring = tostring
local type = type
----------
ffi.cdef[[
struct inotify_event {
int wd;
uint32_t mask;
uint32_t cookie;
uint32_t len;
// char name[];
};
]]
local api = { IN=IN }
local getErrnoString = posix.getErrnoString
local inotify_event_t = ffi.typeof("struct inotify_event")
local sizeof_inotify_event_t = tonumber(ffi.sizeof(inotify_event_t))
local MaxEventsInBatch = 128
local EventBatch = ffi.typeof("$ [$]", inotify_event_t, MaxEventsInBatch)
api.init = class
{
function(flags)
check(flags == nil or type(flags) == "number",
"<flags> must be nil or a number", 2)
local fd = (flags == nil) and C.inotify_init() or C.inotify_init1(flags)
if (fd == -1) then
local funcname = (flags == nil) and "inotify_init" or "inotify_init1"
error(funcname.."() failed: "..getErrnoString())
end
return {
fd = posix.Fd(fd)
}
end,
--[[
-- TODO: implement
__gc = function(self)
self:close()
end,
--]]
getRawFd = function(self)
check(self.fd.fd ~= -1, "must call before closing", 2)
return self.fd.fd
end,
close = function(self)
if (self.fd.fd ~= -1) then
self.fd:close()
end
end,
add_watch = function(self, pathname, mask)
check(type(pathname) == "string", "<pathname> must be a string", 2)
check(type(mask) == "number", "<mask> must be a number", 2)
local wd = C.inotify_add_watch(self.fd.fd, pathname, mask)
if (wd == -1) then
error("inotify_add_watch() on '"..pathname.."' failed: "..getErrnoString())
end
assert(wd >= 0)
return wd
end,
waitForEvents = function(self)
local events, bytesRead = self.fd:readInto(EventBatch(), true)
assert(bytesRead % sizeof_inotify_event_t == 0)
local eventCount = tonumber(bytesRead) / sizeof_inotify_event_t
local tab = {}
for i = 1, eventCount do
local event = events[i - 1]
assert(event.len == 0)
tab[i] = event
end
return tab
end
}
-- Done!
return api