Skip to content

Instantly share code, notes, and snippets.

@kalloc
Created December 13, 2013 07:46
Show Gist options
  • Save kalloc/7941066 to your computer and use it in GitHub Desktop.
Save kalloc/7941066 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
import signal
import ctypes
import sys
import ctypes.util
import os
from ctypes import (
cast,
c_int,
c_int32,
c_uint32,
c_char_p
)
libc_name = ctypes.util.find_library('c')
libc = ctypes.CDLL(libc_name)
inotify_init = libc.inotify_init
inotify_init.argtypes = []
inotify_init.restype = c_int
inotify_rm_watch = libc.inotify_rm_watch
inotify_rm_watch.argtypes = [c_int, c_int]
inotify_rm_watch.restype = c_int
inotify_add_watch = libc.inotify_add_watch
inotify_add_watch.argtypes = [c_int, c_char_p, c_uint32]
inotify_add_watch.restype = c_int
FOREVER = True
def signal_handler(signal, frame):
global FOREVER
print "exit"
FOREVER = False
signal.signal(signal.SIGINT, signal_handler)
class InotifyEvent(ctypes.Structure):
_fields_ = [
("wd", c_int),
("mask", c_int32),
("cookie", c_int32),
("len", c_int32),
]
@classmethod
def decode(cls, buffer):
event = cast(buffer, ctypes.POINTER(cls))[0]
event.name = buffer[EVENT_SIZE: EVENT_SIZE + event.len]
event.total_len = EVENT_SIZE + event.len
return event
IN_CREATE = 0x00000100
IN_DELETE = 0x00000200
IN_ISDIR = 0x40000000
EVENT_SIZE = ctypes.sizeof(InotifyEvent)
EVENT_BUF_LEN = 1024 * (EVENT_SIZE + 16)
PATH = sys.argv[1] if len(sys.argv) == 2 else '/tmp'
i = 0
fd = inotify_init()
if fd < 0:
raise Exception("inotify_init")
wd = inotify_add_watch(fd, PATH, IN_CREATE | IN_DELETE)
while FOREVER:
buffer = os.read(fd, EVENT_BUF_LEN)
buffer = ctypes.create_string_buffer(buffer)
while buffer:
event = InotifyEvent.decode(buffer)
if event.len:
if event.mask & IN_CREATE:
if event.mask & IN_ISDIR:
print "New directory %s/%s created" % (PATH, event.name)
else:
print "New file %s/%s created" % (PATH, event.name)
elif event.mask & IN_DELETE:
if event.mask & IN_ISDIR:
print "Directory %s/%s deleted" % (PATH, event.name)
else:
print "File %s/%s deleted" % (PATH, event.name)
buffer = buffer[event.total_len:]
inotify_rm_watch(fd, wd)
os.close(fd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment