Skip to content

Instantly share code, notes, and snippets.

@demotomohiro
Created March 8, 2023 05:55
Show Gist options
  • Save demotomohiro/8cfe667d80a41de2dc6f4e8d1186c7b3 to your computer and use it in GitHub Desktop.
Save demotomohiro/8cfe667d80a41de2dc6f4e8d1186c7b3 to your computer and use it in GitHub Desktop.
Example Nim code to use inotify on Linux
# https://nim-lang.org/docs/inotify.html
import std/[macros, os]
import posix, posix/inotify
macro testMasks(v: uint32; m: untyped; mstr: untyped; masks: varargs[untyped]): untyped =
masks.expectMinLen 2
result = newStmtList()
let userCode = masks[^1]
for i in 0 ..< (masks.len - 1):
let
mask = masks[i]
maskStr = mask.toStrLit
result.add quote do:
if (`v` and `mask`) != 0:
let
`m` = `mask`
`mstr` = `maskStr`
`userCode`
if paramCount() != 1:
quit "Usage: " & getAppFilename() & " <file_to_watch>"
let
targetPath = paramStr(1)
inoty = inotify_init()
doAssert inoty >= 0
let fileWatch = inotify_add_watch(inoty, targetPath, IN_ACCESS or IN_MODIFY or IN_ATTRIB or IN_CLOSE_WRITE or IN_OPEN)
doAssert fileWatch >= 0
var buf = newSeq[byte](8192)
while (let n = read(inoty, buf[0].addr, buf.len); n) > 0:
for e in inotify_events(buf[0].addr, n):
let m = e[].mask
testMasks(m, mask, maskName, IN_ACCESS, IN_MODIFY, IN_ATTRIB, IN_CLOSE_WRITE, IN_OPEN):
echo maskName
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment