Last active
January 26, 2025 21:30
-
-
Save M0r13n/1202b9efa7438023896a2499c970a576 to your computer and use it in GitHub Desktop.
Play around with the inotify C-API in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
import select | |
import pathlib | |
from ctypes import c_char_p, c_int, c_uint32 | |
import os | |
class EventStruct(ctypes.Structure): | |
_fields_ = ( | |
("wd", c_int), | |
("mask", c_uint32), | |
("cookie", c_uint32), | |
("len", c_uint32), | |
) | |
IN_MODIFY = 0x00000002 | |
IN_CREATE = 0x00000100 | |
path = pathlib.Path('.').absolute() | |
libc = ctypes.CDLL(None) | |
inotify_add_watch = ctypes.CFUNCTYPE(c_int, c_int, c_char_p, c_uint32, use_errno=True)(("inotify_add_watch", libc)) | |
inotify_init = ctypes.CFUNCTYPE(c_int, use_errno=True)(("inotify_init", libc)) | |
inotify_fd = inotify_init() | |
print(f'Created FD: {inotify_fd}') | |
poller = select.poll() | |
poller.register(inotify_fd, select.POLLIN) | |
wd = inotify_add_watch(inotify_fd, str(path).encode(), IN_MODIFY | IN_CREATE ) | |
while True: | |
print('Polling') | |
fd, _ = poller.poll()[0] | |
if fd == inotify_fd: | |
data = os.read(inotify_fd, 0xfff) | |
print(data) | |
struct = EventStruct.from_buffer_copy(data) | |
print(struct.wd) | |
print(struct.mask) | |
print(struct.cookie) | |
print(struct.len) | |
name = data[16 : 16 + struct.len].rstrip(b"\0") | |
print(name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment