| 1 |
# |
| 2 |
# |
| 3 |
# Copyright (C) 2017 Red Hat, Inc. |
| 4 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 5 |
|
| 6 |
|
| 7 |
import ctypes |
| 8 |
import os |
| 9 |
import struct |
| 10 |
import sys |
| 11 |
|
| 12 |
IN_CLOSE_WRITE = 0x00000008 |
| 13 |
IN_MOVED_FROM = 0x00000040 |
| 14 |
IN_MOVED_TO = 0x00000080 |
| 15 |
IN_CREATE = 0x00000100 |
| 16 |
IN_DELETE = 0x00000200 |
| 17 |
IN_DELETE_SELF = 0x00000400 |
| 18 |
IN_MOVE_SELF = 0x00000800 |
| 19 |
IN_IGNORED = 0x00008000 |
| 20 |
|
| 21 |
|
| 22 |
class Inotify: |
| 23 |
def __init__(self): |
| 24 |
self._libc = ctypes.CDLL(None, use_errno=True) |
| 25 |
self._get_errno_func = ctypes.get_errno |
| 26 |
|
| 27 |
self._libc.inotify_init.argtypes = [] |
| 28 |
self._libc.inotify_init.restype = ctypes.c_int |
| 29 |
self._libc.inotify_add_watch.argtypes = [ctypes.c_int, ctypes.c_char_p, |
| 30 |
ctypes.c_uint32] |
| 31 |
self._libc.inotify_add_watch.restype = ctypes.c_int |
| 32 |
self._libc.inotify_rm_watch.argtypes = [ctypes.c_int, ctypes.c_int] |
| 33 |
self._libc.inotify_rm_watch.restype = ctypes.c_int |
| 34 |
|
| 35 |
self.fd = self._libc.inotify_init() |
| 36 |
|
| 37 |
def add_watch(self, path, mask): |
| 38 |
path = ctypes.create_string_buffer(path.encode(sys.getfilesystemencoding())) |
| 39 |
wd = self._libc.inotify_add_watch(self.fd, path, mask) |
| 40 |
if wd < 0: |
| 41 |
sys.stderr.write("can't add watch for %s: %s\n" % (path, os.strerror(self._get_errno_func()))) |
| 42 |
return wd |
| 43 |
|
| 44 |
def rem_watch(self, wd): |
| 45 |
if self._libc.inotify_rm_watch(self.fd, wd) < 0: |
| 46 |
sys.stderr.write("can't remove watch: %s\n" % (os.strerror(self._get_errno_func()))) |
| 47 |
|
| 48 |
def process(self, callback): |
| 49 |
buf = os.read(self.fd, 4096) |
| 50 |
pos = 0 |
| 51 |
while pos < len(buf): |
| 52 |
(wd, mask, _cookie, name_len) = struct.unpack('iIII', buf[pos:pos + 16]) |
| 53 |
pos += 16 |
| 54 |
(name,) = struct.unpack('%ds' % name_len, buf[pos:pos + name_len]) |
| 55 |
pos += name_len |
| 56 |
callback(wd, mask, name.decode().rstrip('\0')) |
| 57 |
|
| 58 |
def run(self, callback): |
| 59 |
while True: |
| 60 |
self.process(callback) |