#include <stdio.h>
#include <sys/epoll.h>
#include <sys/inotify.h>
int g_epollFd;
char event_buf[512];
int main(int argc, char *const *argv) {
int i, ret;
int fd, wd;
int nfds;
int event_pos = 0;
int event_size = 0;
struct epoll_event ev,events[5];
struct inotify_event *inotify_event;
for (i = 1; i < argc; i++) {
printf("arg %d is %s\r\n", i, argv[i]);
}
g_epollFd = epoll_create(10);
if (g_epollFd == -1) {
printf("g_epollFd error\r\n");
return -1;
}
fd = inotify_init();
if (fd == -1) {
printf("fd error\r\n");
return -1;
}
printf("EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLET %u %u %u %u\r\n", EPOLLIN, EPOLLERR, EPOLLHUP, EPOLLET);
printf("IN_CREATE | IN_DELETE | IN_MODIFY %u %u %u\r\n", IN_CREATE, IN_DELETE, IN_MODIFY);
wd = inotify_add_watch(fd, argv[1], IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd == -1) {
printf("inotify_add_watch error\r\n");
return -1;
}
ev.data.fd = fd;
ev.events = EPOLLIN | EPOLLERR | EPOLLHUP | EPOLLET;
if (epoll_ctl(g_epollFd, EPOLL_CTL_ADD, fd, &ev) == -1) {
printf("epoll_ctl error\r\n");
return -1;
}
for ( ; ; ) {
nfds = epoll_wait(g_epollFd, events, 5, -1);
for (i = 0; i < nfds; i++) {
event_pos = 0;
if(events[i].data.fd == fd) {
printf("epoll event %d\r\n", events[i].events);
ret = read(fd, event_buf, sizeof(event_buf));
if(ret < (int)sizeof(struct inotify_event))
{
printf("counld not get event!\n");
return -1;
}
while( ret >= (int)sizeof(struct inotify_event) )
{
inotify_event = (struct inotify_event*)(event_buf + event_pos);
printf("inotify_event->len %d\r\n", inotify_event->len);
printf("inotify event %d\r\n", inotify_event->mask);
if(inotify_event->len)
{
if(inotify_event->mask & IN_CREATE)
{
printf("create file: %s\n", inotify_event->name);
}
else if (inotify_event->mask & IN_DELETE)
{
printf("delete file: %s\n", inotify_event->name);
}
else
{
printf("modify file: %s\n", inotify_event->name);
}
}
event_size = sizeof(struct inotify_event) + inotify_event->len;
ret -= event_size;
event_pos += event_size;
}
}
}
}
(void)inotify_rm_watch(fd, wd);
close(fd);
close(g_epollFd);
}
gcc main.c -o main
./main /home/
另起控制台 /home/ 下增删改文件
网友评论