Add iterator inotify_events which is *almost always* needed logic for (#15152)

client code since Linux `inotify` is much like Linux `getdents64`.

Expanding on "almost always"..The only time that this `iterator` logic
is ***not*** needed on the output of a `read` from inotify fd's is when
one passes a length to `read` *guaranteed* to only pass one event struct
in the buffer.  That unusual circumstance requires (at least!) knowing
the length of the delivered filename before an event occurs, and the
filename itself is optional for some event types.

It is *far* more common to not know lengths in advance which means one
passes a buffer big enough for at least one maximum length directory
entry (256 bytes) which is then also big enough for *many* "typical"
length entries and therefore many events.  In such more common scenarios
this iterator logic is definitely needed.

Further, not using this logic, yet treating the return from read as "the
whole answer" can test ok on "thin" event streams (e.g. 1 event per ms),
hiding a latent bug of processing only the first event.
This commit is contained in:
c-blake
2020-08-08 01:26:20 -04:00
committed by GitHub
parent eee3b189ff
commit 0bc8dd0b00

View File

@@ -73,6 +73,20 @@ proc inotify_rm_watch*(fd: cint; wd: cint): cint {.cdecl,
importc: "inotify_rm_watch", header: "<sys/inotify.h>".}
## Remove the watch specified by WD from the inotify instance FD.
iterator inotify_events*(evs: pointer, n: int): ptr InotifyEvent =
## Abstract the packed buffer interface to yield event object pointers.
##
## .. code-block:: Nim
## var evs = newSeq[byte](8192) # Already did inotify_init+add_watch
## while (let n = read(fd, evs[0].addr, 8192); n) > 0: # read forever
## for e in inotify_events(evs[0].addr, n): echo e[].len # echo name lens
var ev: ptr InotifyEvent = cast[ptr InotifyEvent](evs)
var n = n
while n > 0:
yield ev
let sz = InotifyEvent.sizeof + int(ev[].len)
n -= sz
ev = cast[ptr InotifyEvent](cast[uint](ev) + uint(sz))
runnableExamples:
when defined(linux):