Created
January 25, 2019 16:04
-
-
Save joxer/f70bacc31166c3d5131c999496c44ae4 to your computer and use it in GitHub Desktop.
Inotify example
This file contains 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
#include <stdio.h> | |
#include <stdlib.h> | |
#include <errno.h> | |
#include <sys/types.h> | |
#include <sys/inotify.h> | |
#include <unistd.h> | |
#include <limits.h> | |
#include <string.h> | |
#define EVENT_SIZE ( sizeof (struct inotify_event) ) | |
#define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) | |
#define BUF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1)) | |
int main() { | |
char *ptr, *ptr2; | |
char *bufPtr, *bufPtr2; | |
ssize_t numRead; | |
int inotifyFd, wd, wd2; | |
char buf[BUF_LEN] __attribute__ ((aligned(8))); | |
struct inotify_event* event; | |
char *p; | |
inotifyFd = inotify_init(); | |
printf("inotify started\n"); | |
long size = pathconf(".", _PC_PATH_MAX); | |
if ((bufPtr = (char *)malloc((size_t)size)) != NULL) { | |
ptr = getcwd(bufPtr, (size_t)size); | |
} | |
printf("added notify to %s\n", bufPtr); | |
size = pathconf("..", _PC_PATH_MAX); | |
if ((bufPtr2 = (char *)malloc((size_t)size+3)) != NULL) { | |
ptr2 = strcat(getcwd(bufPtr2, (size_t)size), "/.."); | |
} | |
printf("added notify to %s\n", bufPtr2); | |
wd = inotify_add_watch( inotifyFd, bufPtr, IN_ALL_EVENTS ); | |
wd2 = inotify_add_watch( inotifyFd, bufPtr2, IN_ALL_EVENTS ); | |
for(;;) { | |
numRead = read(inotifyFd, buf, BUF_LEN); | |
if (numRead == 0) { | |
printf("read() from inotify fd returned 0!\n"); | |
exit(1); | |
} | |
for (p = buf; p < buf + numRead; ) { | |
event = (struct inotify_event *) p; | |
if(event->wd == wd) { | |
if(event->mask & IN_OPEN) { | |
printf("event from current directory: %d\n", event->mask & IN_OPEN); | |
} | |
} | |
else if(event->wd == wd2) { | |
if(event->mask & IN_OPEN) { | |
printf("event from parent: %d\n", event->mask & IN_OPEN); | |
} | |
} | |
p += sizeof(struct inotify_event) + event->len; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment