问题描述
我正在开发一个监控文件夹和文件的项目,但我不知道 inotify_add_watch
是如何工作的。我在网上搜索了 fd
的作用,但我不明白 man page:
fd
参数是一个文件描述符,引用要修改其监视列表的 inotify 实例。
这是什么意思?
解决方法
fd 是 inotify_init() 或 inotify_init1() 的返回值。
first,use inotify_init() or inotify_init1() to initialize an inotify
instance;
second,return a file descriptor (with a new inotify event queue) fd ;
third,use the returned fd in inotify_add_watch to monitor the file path
you want to monitor.
示例代码:
int fd = inotify_init();
int wd = inotify_add_watch(fd,argv[1],IN_ALL_EVENTS);
for (;;)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(fd,&fds);
if (select(fd + 1,&fds,NULL,NULL) > 0)
{
int len,index = 0;
while (((len = read(fd,&buf,sizeof(buf))) < 0) && (errno == EINTR));
while (index < len)
{
event = (struct inotify_event *)(buf + index);
_inotify_event_handler(event);
index += sizeof(struct inotify_event) + event->len;
}
}
}
inotify_rm_watch(fd,wd);
return 0;
,
文件描述符基本上是一些输入/输出资源的标识符。使用inotify时,需要用inotify_init
初始化一个实例,它返回一个文件描述符,然后你可以用inotify_add_watch
将你想看的文件添加到实例中。
因此,回答您的问题,inotify_add_watch
中的 fd 参数是由 inotify_init
调用返回的 inotify 实例的文件描述符。