Skip to content

Instantly share code, notes, and snippets.

@habibutsu
Created December 13, 2013 14:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save habibutsu/7945015 to your computer and use it in GitHub Desktop.
Save habibutsu/7945015 to your computer and use it in GitHub Desktop.
Example a work with inotify in Python
import os
import sys
import struct
from collections import namedtuple
from ctypes import\
CDLL,\
CFUNCTYPE,\
c_int,\
c_char_p,\
c_uint32
from ctypes.util import find_library
libc_name = None
try:
libc_name = find_library("c")
except (OSError, IOError):
libc_name = 'libc.so.6'
libc = CDLL(libc_name, use_errno=True)
if(not hasattr(libc, 'inotify_init') or
not hasattr(libc, 'inotify_add_watch') or
not hasattr(libc, 'inotify_rm_watch')):
print "libs not supported inotify_init, inotify_add_watch, inotify_rm_watch"
inotify_init = CFUNCTYPE(c_int, use_errno=True)(("inotify_init", libc))
inotify_add_watch = CFUNCTYPE(
c_int, c_int, c_char_p, c_uint32, use_errno=True)(("inotify_add_watch", libc))
inotify_rm_watch = CFUNCTYPE(c_int, c_int, c_uint32, use_errno=True)(
("inotify_rm_watch", libc))
InotifyEvent = namedtuple("InotifyEvent", ["wd", "mask", "cookie", "len", "name"])
def parse_event_buffer(event_buffer, events_list):
"""
struct inotify_event {
__s32 wd; /* watch descriptor */
__u32 mask; /* watch mask */
__u32 cookie; /* cookie to synchronize two events */
__u32 len; /* length (including nulls) of name */
char name[0]; /* stub for possible name */
};
"""
while len(event_buffer) > 16:
data = struct.unpack_from('iIII', event_buffer)
name = event_buffer[16:16 + data[3]].rstrip('\0')
inotify_event = InotifyEvent(*data, name=name)
event_buffer = event_buffer[16 + inotify_event.len:]
events_list.append(inotify_event)
return event_buffer
IN_ACCESS = 0x00000001 # File was accessed.
IN_MODIFY = 0x00000002 # File was modified.
IN_ATTRIB = 0x00000004 # Meta-data changed.
IN_CLOSE_WRITE = 0x00000008 # Writable file was closed.
IN_CLOSE_NOWRITE = 0x00000010 # Unwritable file closed.
IN_OPEN = 0x00000020 # File was opened.
IN_MOVED_FROM = 0x00000040 # File was moved from X.
IN_MOVED_TO = 0x00000080 # File was moved to Y.
IN_CREATE = 0x00000100 # Subfile was created.
IN_DELETE = 0x00000200 # Subfile was deleted.
IN_DELETE_SELF = 0x00000400 # Self was deleted.
IN_MOVE_SELF = 0x00000800 # Self was moved.
EVENT_BUFFER_SIZE = 1024
inotify_fd = inotify_init()
if(inotify_fd == -1):
sys.exit(-1)
wd = inotify_add_watch(inotify_fd, "example.txt", IN_ACCESS | IN_ATTRIB | IN_MODIFY)
events_list = []
event_buffer = ""
while True:
event_buffer += os.read(inotify_fd, EVENT_BUFFER_SIZE)
event_buffer = parse_event_buffer(event_buffer, events_list)
if events_list:
event = events_list.pop()
print event
inotify_rm_watch(inotify_fd, wd)
os.close(inotify_fd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment