Skip to content

Instantly share code, notes, and snippets.

@javiermon
Last active June 7, 2017 06:00
Show Gist options
  • Select an option

  • Save javiermon/02f05fa5a8e246786d01 to your computer and use it in GitHub Desktop.

Select an option

Save javiermon/02f05fa5a8e246786d01 to your computer and use it in GitHub Desktop.
inotify_directory.c
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <linux/inotify.h>
#include <signal.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
static int fd, wd;
void cleanup(void)
{
inotify_rm_watch(fd, wd);
close(fd);
}
void intHandler(int dummy) {
printf("QUIT\n");
cleanup();
exit(0);
}
int main(int argc,char *argv[])
{
int length;
char buffer[EVENT_BUF_LEN];
signal(SIGINT, intHandler);
if (argc != 2) {
printf("Usage: %s directory\n",argv[0]);
return 1;
}
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
}
if (inotify_add_watch(fd, argv[1], IN_CREATE | IN_DELETE) == -1)
{
perror("inotify_add_watch");
}
while (1)
{
int i = 0;
char path[128];
struct inotify_event *event = ( struct inotify_event * ) &buffer[i];
/* blocks until the change event occurs */
length = read(fd, buffer, EVENT_BUF_LEN);
if (length < 0) {
perror("read");
}
if (event->len) {
if (event->mask & IN_CREATE) {
if (event->mask & IN_ISDIR) {
printf("New directory %s created.\n", event->name);
sprintf(path, "%s/%s", argv[1], event->name);
if (inotify_add_watch(fd, path, IN_CREATE | IN_DELETE) == -1)
{
perror("inotify_add_watch");
}
}
else {
printf("New file %s created.\n", event->name);
}
}
else if (event->mask & IN_DELETE) {
if (event->mask & IN_ISDIR) {
printf("Directory %s deleted.\n", event->name);
sprintf(path, "%s/%s", argv[1], event->name);
if (inotify_rm_watch(fd, path, IN_CREATE | IN_DELETE) == -1)
{
perror("inotify_rm_watch");
}
}
else {
printf("File %s deleted.\n", event->name);
}
}
}
i += EVENT_SIZE + event->len;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment