demo
This commit is contained in:
99
inotify/demo.c
Normal file
99
inotify/demo.c
Normal file
@@ -0,0 +1,99 @@
|
||||
// build command: gcc demo.c -o demo
|
||||
|
||||
#define _POSIX_SOURCE 0
|
||||
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <sys/inotify.h>
|
||||
|
||||
extern int errno;
|
||||
int fd;
|
||||
|
||||
void handler(int signo, siginfo_t *info, void *context) {
|
||||
printf("interrupted\n");
|
||||
close(fd);
|
||||
exit(EXIT_SUCCESS);
|
||||
}
|
||||
|
||||
void print_event_name(struct inotify_event *event) {
|
||||
if (event->len > 0) {
|
||||
printf("event on %s\n", event->name);
|
||||
} else {
|
||||
printf("\n");
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
errno = 0;
|
||||
|
||||
struct sigaction act = { 0 };
|
||||
act.sa_flags = SA_SIGINFO;
|
||||
act.sa_sigaction = &handler;
|
||||
|
||||
if (sigaction(SIGINT, &act, NULL) == -1) {
|
||||
perror("sigaction");
|
||||
return(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
fd = inotify_init();
|
||||
if (fd == -1) {
|
||||
perror("inotify_init");
|
||||
return(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
int wd = inotify_add_watch(fd, "/home/yono/watchdir", IN_OPEN|IN_CLOSE|IN_DELETE);
|
||||
if (wd == -1) {
|
||||
perror("inotify_add_watch");
|
||||
close(fd);
|
||||
return(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
struct inotify_event *event;
|
||||
uint8_t buf[1024];
|
||||
ssize_t len;
|
||||
uint32_t start = 0;
|
||||
while (1) {
|
||||
len = read(fd, buf + start, 1024);
|
||||
if (len == -1) {
|
||||
perror("read");
|
||||
close(fd);
|
||||
return(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
while(len >= 0x10) {
|
||||
event = (struct inotify_event *)buf;
|
||||
switch(event->mask) {
|
||||
case IN_OPEN:
|
||||
printf("open: ");
|
||||
print_event_name(event);
|
||||
break;
|
||||
case IN_CLOSE_WRITE:
|
||||
case IN_CLOSE_NOWRITE:
|
||||
printf("close: ");
|
||||
print_event_name(event);
|
||||
break;
|
||||
case IN_DELETE:
|
||||
printf("delete: ");
|
||||
print_event_name(event);
|
||||
break;
|
||||
}
|
||||
|
||||
if (0x10 + event->len <= len) {
|
||||
uint32_t evlen = event->len;
|
||||
memcpy(buf, buf + 0x10 + evlen, len - 0x10 - evlen);
|
||||
|
||||
len = len - 0x10 - evlen;
|
||||
}
|
||||
}
|
||||
start = len;
|
||||
}
|
||||
|
||||
|
||||
close(fd);
|
||||
printf("hello world\n");
|
||||
return(0);
|
||||
}
|
||||
Reference in New Issue
Block a user