#include <sys/inotify.h>
#include <sys/epoll.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/ioctl.h>
#include <string.h>
struct inotify_data_type{
int fd;
char self_type[16];
};
int main(int argc,char* argv[]){
if(argc < 2) {
return 1;
}
int inotify_fd = inotify_init();
if(inotify_fd < 0){
printf("Create inotify descriptor failed.");
return 1;
}
int *wd = malloc(sizeof(int)*(argc-1));
int i;
for(i = 1; i < argc; i++){
wd[i-1] = inotify_add_watch(inotify_fd,argv[i],IN_CLOSE_WRITE);
if(wd[i-1] < 0){
printf("Could not watch dirctory : %s");
return 1;
}
}
int nb = 1;
ioctl(inotify_fd,FIONBIO,&nb);
int epoll_fd = epoll_create(1024);
if(epoll_fd < 0){
printf("Create epoll descriptor failed");
return 1;
}
struct inotify_data_type inotify_data;
inotify_data.fd = inotify_fd;
strcpy(inotify_data.self_type,"inotify");
struct epoll_event inotify_event;
int option = EPOLL_CTL_ADD;
inotify_event.events = EPOLLIN|EPOLLET;
inotify_event.data.ptr = &inotify_data;
int result = epoll_ctl(epoll_fd, option, inotify_fd, &inotify_event);
if(result < 0){
printf("Could not add Inotify event in EPOLL");
return 1;
}
int running = 1;
struct epoll_event event_list[10];
while(running){
int events_num = epoll_wait(epoll_fd, event_list,10,0);
if(events_num < 0){
printf("Epoll_wait failed!");
return 1;
}
if(events_num > 0){
// int i = 0;
for(i = 0; i < events_num; i++){
struct inotify_data_type *inotify_data_backup = event_list[i].data.ptr;
if(strcmp(inotify_data_backup->self_type,"inotify") == 0){
int revents = event_list[i].events;
if(re
epoll模型添加inotify事件的代码实现
最新推荐文章于 2023-10-13 13:09:56 发布